snippetphpMinor
Generate 6 random numbers for lottery in PHP
Viewed 0 times
randomphpnumbersgeneratelotteryfor
Problem
This program generates 6 random numbers between 0 and 45 and the numbers cannot be repeated. Can this code be improved?
$numbers = [];
$i = 1;
while($i <= 6)
{
$number = mt_rand(0, 45);
if(!in_array($number, $numbers))
{
array_push($numbers, $number);
$i++;
}
}
sort($numbers);
echo implode(" - ", $numbers);Solution
Your algorithm is functional, but is not necessarily very efficient, and it will collide more, and more often if the count of numbers increases.
It's generally neater to start off with a unique set of numbers, and to extract a random selection of those numbers, instead of selecting random numbers, and testing for uniqueness.
PHP makes this relatively neat, because it has a built-in shuffle function (that's essentially doing a Fisher-Yates shuffle using the same random system that you are).
So, get an array of the unique values, shuffle it, take a selection of it, and sort the result:
Note, using named variables instead of constants makes it clearer what you are doing.
See this running on ideone: https://ideone.com/1Hh0y8
It's generally neater to start off with a unique set of numbers, and to extract a random selection of those numbers, instead of selecting random numbers, and testing for uniqueness.
PHP makes this relatively neat, because it has a built-in shuffle function (that's essentially doing a Fisher-Yates shuffle using the same random system that you are).
So, get an array of the unique values, shuffle it, take a selection of it, and sort the result:
$count = 6;
$highball = 45;
$numbers = range(0, $highball);
shuffle($numbers);
$drawn = array_slice($numbers, - $count);
sort($drawn);Note, using named variables instead of constants makes it clearer what you are doing.
See this running on ideone: https://ideone.com/1Hh0y8
Code Snippets
$count = 6;
$highball = 45;
$numbers = range(0, $highball);
shuffle($numbers);
$drawn = array_slice($numbers, - $count);
sort($drawn);Context
StackExchange Code Review Q#124223, answer score: 5
Revisions (0)
No revisions yet.