mercredi 8 novembre 2017

random_int instead of array_rand in a loop with no doubles

I'm trying to create a generator for a lotto that I play very often.
The lotto is a 5 number draw, ranging from number 1-50 and the same number cannot appear again.

My current approach to do this is using array_rand() but after some reading I noticed that I should not use array_rand() for this purpose, instead I should be using random_int().

My current approach below:

$numbers = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50);
 for ($i = 0; $i <= 4; $i++) {
    $number = array_rand($numbers);
    unset($numbers[$number]);
 if ($number == 0) {
    $number = array_rand($numbers);
    unset($numbers[$number]);
 }
    $out1[] = array("<div class=\"number\">$number</div>");
 }

As you can see above, this works and it generates 5 numbers without duplicating because I unset the number after it's been drawn.

My question is:
How can I do the same as above but using random_int()instead?

To clarify: Use random_int() to generate a random number but assure that it doesnt generate the same number again.




Aucun commentaire:

Enregistrer un commentaire