我可以使用哪个函数来验证nexts 99999999 ids中是否会有冲突?谢谢!
发布于 2012-03-18 23:41:51
如果您的哈希函数按假设工作,并且总是为相同的输入生成相同的输出。并且您的输入被限制为99999999个数字,您可以简单地为这些数字生成散列并验证是否没有重复的数字。
尽管最好的解决方案是从数学上证明您的散列函数将为这些数字产生唯一的结果。
发布于 2012-03-19 00:42:17
如果散列可以是完全随机的,请尝试使用其中的当前时间戳作为额外的随机数生成器。例如:
$hash = sha1(microtime() * rand(1, 9999));复制出来的可能性相当小。此外,尝试将数据库字段设置为UNIQUE字段,确保不会重复插入。然后,为了完成任务,您可以创建一个尝试直到成功的循环,如下所示:
// SHA1 values shouldn't need escaping, but it doesn't really hurt to be extra sure :)
$query = "INSERT INTO `table` (`hash`) VALUES('" . mysql_real_escape_string($hash) . "')";
// Let's try the insert with a max of 10 random hashes
$tries = 10;
while(mysql_query($query) !== true) {
if($tries <= 0) {
break; // Something is really failing, stop trying!
}
// If this point is reached, apparantly a duplicate was created. Try again.
$hash = sha1(microtime() * rand(1, 9999));
// Decrement the tries counter.
$tries--;
}https://stackoverflow.com/questions/9759352
复制相似问题