note 82579 deleted from function.mt-rand by cmb

From: Date: Sun, 19 Jan 2020 08:39:34 +0000
Subject: note 82579 deleted from function.mt-rand by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-213917@lists.php.net to get a copy of this message
Note Submitter: Jonathon ---- 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"; } ?>

« previous php.notes (#213917) next »