Last active
May 17, 2016 08:39
-
-
Save rakkang/30093e6d9f1b6262efd3 to your computer and use it in GitHub Desktop.
生成伪均匀分布的随机序列
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 | |
/** | |
* Rang = [$start, $end] | |
*/ | |
function gen_rand_serial($count, $start, $end) | |
{ | |
$R = $end - $start + 1; | |
$count = min($R, $count); | |
if ($R == $count) { | |
for ($i = $start; $i < $end + 1; $i++) { | |
$res[] = $i; | |
} | |
} else { | |
$f = floor($R / $count); | |
$N = $count; | |
$reverse = $f == 1; | |
if ($reverse) { | |
$N = $R - $count; | |
$f = floor($R / $N); | |
} | |
for ($i = 0; $i < $N; ++$i) { | |
$min = min($start + $i * $f, $end); | |
$max = min($start + ($i + 1) * $f - 1, $end); | |
if ($i == $N - 1) { | |
$max = max($max, $end); | |
} | |
$res[] = mt_rand($min, $max); | |
echo "(" . $min . "-" . $max . ")\n"; | |
} | |
if ($reverse) { | |
$new_res = array(); | |
for ($i = $start; $i <= $end; ++$i) { | |
if (!in_array($i, $res)) { | |
$new_res[] = $i; | |
} | |
} | |
$res = $new_res; | |
} | |
} | |
return $res; | |
} | |
array_shift($argv); | |
if (count($argv) < 3) { | |
echo "Parameters illegal\n"; | |
print_r($argv); | |
} else { | |
$res = gen_rand_serial((int) $argv[0], (int) $argv[1], (int) $argv[2]); | |
if ($res) { | |
print_r($res); | |
} else { | |
echo "Error! Res = " . json_encode($res) . "\n"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment