note 82579 added to function.mt-rand
| From: | Jonathon at osu1 dot php dot net | Date: | Thu, 17 Apr 2008 08:14:00 +0000 |
| Subject: | note 82579 added to function.mt-rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-138393@lists.php.net to get a copy of this message | ||
Below, andrei suggested a function for generating a list of unique integers, randomly arranged. In
response to a note below that his solution is inefficient, I'm providing an O(N) solution which
should be much more efficient, yet still yield a good guarantee of producing randomly ordered
integers.
<?php
function SwapShuffle($min, $max) {
$last = $max - $min;
for ($i=0; $i<=$last; $i++) {
$arr[$i] = $min + $i;
}
for ($run=0; $run<7; $run++) {
for ($i=0; $i<=$last; $i++) {
$target = mt_rand(0, $last);
$swap = $arr[$target];
$arr[$target] = $arr[$i];
$arr[$i] = $swap;
}
}
return $arr;
}
// Call as:
$result = SwapShuffle(10, 30);
foreach ($result as $num) {
echo "$num\n";
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 128.195.107.72
----
Manual Page -- http://www.php.net/manual/en/function.mt-rand.php
Edit -- https://master.php.net/note/edit/82579
Del: integrated -- https://master.php.net/note/delete/82579/integrated
Del: useless -- https://master.php.net/note/delete/82579/useless
Del: bad code -- https://master.php.net/note/delete/82579/bad+code
Del: spam -- https://master.php.net/note/delete/82579/spam
Del: non-english -- https://master.php.net/note/delete/82579/non-english
Del: in docs -- https://master.php.net/note/delete/82579/in+docs
Del: other reasons-- https://master.php.net/note/delete/82579
Reject -- https://master.php.net/note/reject/82579
Search -- https://master.php.net/manage/user-notes.php