here comes my first question on SO.
I'm currently working on a website and I have to generate 6 numbers between 1 and 29 (one of each max) for a lottery. As they can be in any order, I simply sort them afterwards.
If I'm not mistaken, it should mean that there's (29*28*27*26*25*24) / 6! = 475020 different possible combinations.
I've tried different ways of genereting the sequences, either using mt_rand or random_int (from random_compat) but when I test it with something like 10k iterations, I always get around 100 duplicates, even though they are like 465k combinations still available.
Here are the code samples I've been trying :
// Using an array and mt_rand (or random_int, giving same results)
// Also tried shuffling the array instead of simply reindexing it, not better
$values = range(1, 29);
while(count($values) > 6) {
unset($values[mt_rand(0, count($values) - 1)]);
$values = array_values($values);
}
// Creating the array from random numbers (same results using random_int)
$values = array();
while (count($values) < 6) {
$r = mt_rand(1, 29);
if (in_array($r, $values)) {
continue;
} else {
$values[] = $r;
}
}
So well... My questions are :
- Is there a way to improve what I'm currently doing ?
- Is that the way it's gonna be and I have to deal with it ?
- Am I simply doing it wrong ?
Thanks !
Lyn.
PS : Looked through many questions, but didn't find anything filling my needs, sorry if I didn't look well enough !
Aucun commentaire:
Enregistrer un commentaire