Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Created August 31, 2017 04:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save thinkphp/137c8438af4a7e92c2beedd00f8897e9 to your computer and use it in GitHub Desktop.
Save thinkphp/137c8438af4a7e92c2beedd00f8897e9 to your computer and use it in GitHub Desktop.
<?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>";
?>
@douglashb
Copy link

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;
}

 return $arr;

}

$arr = [1, 2, 3, 4];

print_r($arr);
print_r(myShuffle($arr));

I hope help you.

Best regards.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment