Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing 1 to 1000 without loop or conditionals - in PHP

Tags:

php

Idea taken from here - this time you can only use PHP. Is this even possible?

like image 987
Sam Avatar asked Mar 14 '11 22:03

Sam


3 Answers

Here's an interesting oo solution based on PHP's overloading:

class thousand_printer {
   public function __construct() {
      $this->print1();
   }

   public function __call($method, $_) {
      $count = str_replace('print', '', $method);
      echo "$count ";
      $this->{"print" . ++$count}();
   }

   public function print1000() {
      echo "1000\n";
   }
}

new thousand_printer;

I'm glad my solution is so popular. Here's a slight improvement that offers some modularity:

class printer {
   public function __construct() {
      $this->print1();
   }
   public function __call($method, $_) {
      $count = str_replace('print', '', $method);
      echo "$count ";
      $this->{"print" . ++$count}();
   }
}

class thousand_printer extends printer {
   public function print1001() {}
}

new thousand_printer;
like image 150
Explosion Pills Avatar answered Oct 24 '22 23:10

Explosion Pills


print implode("\n", range(1, 1000)); 
like image 27
vicTROLLA Avatar answered Oct 25 '22 01:10

vicTROLLA


<?php

    class Evil
    {
        function __construct($c) {
            $this->c = $c;
        }

        function __call($name, $args) {
            echo $this->c . "\n";
            $this->c += 1;
            $this->tick();
        }

        // The bomb
        function tick() {
            call_user_func(__NAMESPACE__ .'\Evil::__' . $this->c);
        }

        // 007 
        function __1000() {}
    }

    $devil = new Evil(1);
    $devil->tick();

?>
like image 36
miku Avatar answered Oct 25 '22 00:10

miku