Skip to content

Instantly share code, notes, and snippets.

@Hailong
Created November 27, 2019 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hailong/72c7dfe91253be64a4f9e31e4dce4c7e to your computer and use it in GitHub Desktop.
Save Hailong/72c7dfe91253be64a4f9e31e4dce4c7e to your computer and use it in GitHub Desktop.
Randomness distribution test of different random functions
#!/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