php序号发生器,数字重组,可以隐藏原来的1,2,3。。。
一个晚上的成果,原理:
将1,2,3,4,5,6,7,8,9,0映射到9,5,1,0,4,8,7,3,2,6
同理映射base,base有1-10种数组,也就是可以一位数到10位数
$base 实际上是下面的根据下面数组处理得来的。
array(
array(0),
array(1,0),
array(2,0,1),
array(3,0,2,1),
array(4,0,1,3,2),
array(5,1,0,4,3,2),
array(6,2,0,4,5,1,3),
array(7,3,0,4,6,2,1,5),
array(8,4,0,1,5,7,3,2,6),
array(9,5,1,0,4,8,7,3,2,6)
);
参数$num是种子数,$m是结果位数,$offset一个偏移值(可以更有效的打乱数字)。
function seq10($num, $m, $offset = 0) { static $seq = array(9,5,1,0,4,8,7,3,2,6); static $base = array( array(1,10), array(10,1,100), array(100,1,10,1000), array(1000,1,100,10,10000), array(10000,1,10,1000,100,100000), array(100000,10,1,10000,1000,100,1000000), array(1000000,100,1,10000,100000,10,1000,10000000), array(10000000,1000,1,10000,1000000,100,10,100000,100000000), array(100000000,10000,1,10,100000,10000000,1000,100,1000000,1000000000), array(1000000000,100000,10,1,10000,100000000,10000000,1000,100,1000000,10000000000) ); $res = $num; for ($i = 0; $i < 16; $i++) { $num = 0; for ($j = 0; $j < $m; $j++) { $num += $seq[$res % 10] * $base[$m-1][$j]; $res /= 10; } $res = ($num + $offset + $i) % $base[$m-1][$m]; } return $res; }
通过调用上面的函数,便可以进行任意数字映射,如1-100映射结果到1-100
$arr = array(); $start = microtime(true); for ($i = 1; $i < 100; $i++) $arr[$i] = seq10($i, 2, 12); $end = microtime(true); print_r($arr); echo count($arr)."\n"; echo $end - $start; 结果: E:\>php seq.php Array ( [1] => 8 [2] => 88 [3] => 16 [4] => 75 [5] => 0 [6] => 58 [7] => 70 [8] => 91 ... [90] => 29 [91] => 51 [92] => 66 [93] => 23 [94] => 62 [95] => 54 [96] => 22 [97] => 3 [98] => 34 [99] => 72 ) 99 0.002357006072998
1-10映射到6位数
$arr = array(); $start = microtime(true); for ($i = 1; $i < 10; $i++) $arr[$i] = seq10($i, 6, 123456); $end = microtime(true); print_r($arr); echo count($arr)."\n"; echo $end - $start; E:\>php seq.php Array ( [1] => 721627 [2] => 782511 [3] => 256581 [4] => 969508 [5] => 451505 [6] => 928354 [7] => 302664 [8] => 387627 [9] => 817626 ) 9 0.00050187110900879
唯一性验证:
$arr = array(); $start = microtime(true); for ($i = 0; $i < 1000000; $i++) $arr[seq10($i, 6, 123456)] = 1; $end = microtime(true); //print_r($arr); echo count($arr)."\n"; echo $end - $start; E:\>php seq.php 1000000 36.970967054367
几许风雨天,千里孤月夜。日出似无时,何处现流光。