-
-
Save pschultz/44bee17e7ffe9579aeb14747aa818fea to your computer and use it in GitHub Desktop.
PHP: seeded shuffle via usort
This file contains 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 | |
$dist = []; | |
mt_srand(1337); | |
for ($i = 0; $i < 10000; $i++) { | |
$a = range('A', 'E'); | |
usort($a, function() { return mt_rand(-1, 1); }); | |
#shuffle($a); | |
foreach ($a as $k => $v) { | |
$dist[$v][$k+1] = ($dist[$v][$k+1] ?? 0) + 1; | |
} | |
} | |
foreach ($dist as $v => &$a) { | |
ksort($a); | |
} | |
ksort($dist); | |
echo <<<EOS | |
Given a list of five values, 'A' through 'E', if we shuffle them 10,000 | |
times, we expect each value to appear in any given position about 2,000 | |
times: | |
EOS; | |
var_export($dist); | |
echo "\n"; |
This file contains 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
Output with shuffle (and thus no seed): | |
array ( | |
'A' => | |
array ( | |
1 => 2007, | |
2 => 1959, | |
3 => 1871, | |
4 => 2046, | |
5 => 2117, | |
), | |
'B' => | |
array ( | |
1 => 2001, | |
2 => 1979, | |
3 => 2029, | |
4 => 2005, | |
5 => 1986, | |
), | |
'C' => | |
array ( | |
1 => 2055, | |
2 => 1981, | |
3 => 1976, | |
4 => 2022, | |
5 => 1966, | |
), | |
'D' => | |
array ( | |
1 => 2001, | |
2 => 2088, | |
3 => 2004, | |
4 => 2014, | |
5 => 1893, | |
), | |
'E' => | |
array ( | |
1 => 1936, | |
2 => 1993, | |
3 => 2120, | |
4 => 1913, | |
5 => 2038, | |
), | |
) |
This file contains 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
Output with usort: | |
array ( | |
'A' => | |
array ( | |
1 => 5644, | |
2 => 1541, | |
3 => 1739, | |
4 => 776, | |
5 => 300, | |
), | |
'B' => | |
array ( | |
1 => 1035, | |
2 => 5788, | |
3 => 2191, | |
4 => 730, | |
5 => 256, | |
), | |
'C' => | |
array ( | |
1 => 2876, | |
2 => 1694, | |
3 => 3295, | |
4 => 1549, | |
5 => 586, | |
), | |
'D' => | |
array ( | |
1 => 322, | |
2 => 725, | |
3 => 2009, | |
4 => 4679, | |
5 => 2265, | |
), | |
'E' => | |
array ( | |
1 => 123, | |
2 => 252, | |
3 => 766, | |
4 => 2266, | |
5 => 6593, | |
), | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment