Created
November 27, 2019 14:03
-
-
Save Hailong/72c7dfe91253be64a4f9e31e4dce4c7e to your computer and use it in GitHub Desktop.
Randomness distribution test of different random functions
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
#!/usr/bin/env php | |
<?php | |
/** | |
* Randomness distribution test of different random functions | |
*/ | |
$counters = [ | |
'array_rand' => [], | |
'random_int' => [], | |
]; | |
foreach ($counters as $name => &$items) { | |
for ($i=0; $i < 4; $i++) { | |
$items['item' . $i] = 0; | |
} | |
} | |
$runLoop = function ($function, $items) use (&$counters) | |
{ | |
for ($i=0; $i < 1000000; $i++) { | |
switch ($function) { | |
case 'array_rand': | |
$key = $function($items); | |
$counters[$function][$key]++; | |
break; | |
case 'random_int': | |
$keys = array_keys($items); | |
$index = random_int(0, count($keys) - 1); | |
$counters[$function][$keys[$index]]++; | |
break; | |
default: | |
break; | |
} | |
} | |
}; | |
foreach ([ | |
'array_rand', | |
'random_int', | |
] as $function) { | |
$runLoop($function, $counters[$function]); | |
} | |
print_r($counters); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment