Advertisement
chan15

Lottery Algorithm

Feb 15th, 2016
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.86 KB | None | 0 0
  1. <?php
  2.  
  3. class Lottery
  4. {
  5.     private $start;
  6.     private $end;
  7.     public $tempBalls = [];
  8.  
  9.     public function __construct($start = 1, $end = 49)
  10.     {
  11.         $this->start = $start;
  12.         $this->end = $end;
  13.     }
  14.  
  15.     public function balls($num = 5)
  16.     {
  17.         $balls = range($this->start, $this->end);
  18.         $results = [];
  19.  
  20.         do {
  21.             $results[] = $this->randBall($balls);
  22.         } while (count($results) < $num);
  23.  
  24.         $result = implode(', ', $results);
  25.         $this->tempBalls = [];
  26.  
  27.         return $result;
  28.     }
  29.  
  30.     private function randBall($range)
  31.     {
  32.         $ball = $range[mt_rand(0, count($range) - 1)];
  33.  
  34.         if (!in_array($ball, $this->tempBalls)) {
  35.             $this->tempBalls[] = $ball;
  36.         } else {
  37.             return $this->randBall($range);
  38.         }
  39.  
  40.         return $ball;
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement