我刚开始做一个项目,在开始之前我有一些关于一 block 的问题 我需要将代码放在一起,以及它需要如何工作。
此代码将生成序列号,当通过算法运行时,该序列号将等于 一个标识符。该算法没有什么特别之处。
序列号需要分成 4 组,每组 5 个:(最好是十六进制)
示例: 00A00-0B000-F00C0-0000D
标识符将只是一组数字:
示例:15456548
我想要创建的是一个脚本,可以将序列号中的十六进制相加(array_sum?),除以 10 并等于标识符 (15456548)。脚本需要创建尽可能多的序列号实例。
程序示例:
标识符: 22807.4
要制作多少个序列号: 2
序列号:
45154-54587-58458-69875
55457-45584-18658-49578
(这些序列号加起来除以10等于标识符(22807.4)
我不确定是否有人可以帮助我想出一些办法,或者至少可以解释一下过程,但我以前从未在 PHP 中构建过这样的东西。
最佳答案
另一个例子。你需要添加一些东西。希望您在运行该程序时会意识到它们。
<?php
$num = '1234';
$serNums = findSerialNum(1234, 5);
echo var_export($serNums, true);
function findSerialNumSingle($num)
{
$serialNum = array();
$target = $num * 10;
// select some heuristic. We have to generate 5 sets. How shall we
// distribute the numbers between the 5 sets?
// Obviously one set can exceed the num * 10 itself.
// Lets select that as the heuristic, that the first number can be max that.
$remaining = $target;
$soFar = 0;
for($i = 0; $i < 5; $i++)
{
// select the entry that we would fill. Randomize it.
while(true)
{
$idx = rand(0, 4);
if(!isset($serialNum[$idx])) // is the entry already filled in?
break;
}
$t = rand(0, $target - $soFar); // find number between 0 and remain number
$serialNum[$idx] = $t;
$soFar += $t;
}
// put serial number is proper format
$s = '';
for($i = 0; $i < 5; $i++)
{
$s .= sprintf('%05X', $serialNum[$i]) . '-';
}
return $s;
}
function findSerialNum($num, $numInstances)
{
$serNums = array();
for($i = 0; $i < $numInstances; $i++)
{
while(true)
{
// loop till you find a distinct serial number
$t = findSerialNumSingle($num);
if(array_search($t, $serNums) == FALSE)
{
$serNums[$i] = $t;
break;
}
}
}
return $serNums;
}
?>
关于php - 使用 PHP 中的算法生成序列号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14272327/