Created
August 31, 2017 04:40
-
-
Save thinkphp/137c8438af4a7e92c2beedd00f8897e9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* It's an algorithm for generating a random permutation of a finit sequence - in plain terms, the algorithm shuffles the sequence. | |
* | |
* Reference: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle | |
*/ | |
function MyShuffle(&$arr) { | |
for($i = 0; $i < sizeof($arr); ++$i) { | |
$r = rand(0, $i); | |
$tmp = $arr[$i]; | |
$arr[$i] = $arr[$r]; | |
$arr[$r] = $tmp; | |
} | |
}; | |
echo"<h2>Hello Fisher-Yates Shuffle Algorithm</h2>"; | |
$arr = array(0,1,2,3,4,5,6,7,8,9); | |
echo"<pre>"; | |
print_r($arr); | |
echo"</pre>"; | |
MyShuffle($arr); | |
echo"<pre>"; | |
print_r($arr); | |
echo"</pre>"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
An Excelent contribution, but you can better your algomithm, whith the next suggerens:
1º. Not use var with reference, the function has must return your values.(In new versions of php not work the reference)
2º. Not use indexOf(), use count() is more faster and readable for other developers.
3º. The Fisher-Yates Shuffle walk the array in reverse order.
function myShuffle($arr) {
for($i = count($arr) - 1; $i > 0; $i--) {
$r = rand(0, $i);
$tmp = $arr[$i];
$arr[$i] = $arr[$r];
$arr[$r] = $tmp;
}
}
$arr = [1, 2, 3, 4];
print_r($arr);
print_r(myShuffle($arr));
I hope help you.
Best regards.