Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Naive code gen
<?php
$len = 4;
$rand_fun = 'mt_rand';
$usedCodes = array();
$found = 0;
$max = pow(10, $len);
$prevSteps = 0;
$steps = 0;
$stats = array();
while ($found<$max) {
$steps++;
$code = gen_random($len);
if (!in_array($code, $usedCodes)) {
if ($found==0) {
$stats[] = 1;
} else {
$stats[] = $steps-$prevSteps;
}
$prevSteps = $steps;
$found++;
$usedCodes[] = $code;
/*if ($found%100==0) {
mt_srand(microtime(true));
}*/
}
}
echo "Code length: $len\n";
echo "Used random: $rand_fun()\n";
echo "Found: $found\n";
echo "Steps: $steps\n";
echo "Steps per found: ".($steps/$found)."\n";
echo "Max steps: ".call_user_func_array('max', $stats)."\n";
foreach (array_chunk($stats, sizeof($stats)/10) as $i=>$chunk) {
echo "Range ".($i*10)."% - ".(($i+1)*10)."%: ".(array_sum($chunk)/sizeof($chunk))." steps on average, max: ".call_user_func_array('max', $chunk)."\n";
}
function gen_random($len=4) {
global $rand_fun;
$alphabet = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '0');
$code = '';
for ($i=0; $i<$len; $i++) {
$code .= $alphabet[call_user_func($rand_fun,0,9)];
}
return $code;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.