我正在生成应该很短但不应该重复的随机订单跟踪号。
对于由 3 位数字组成的跟踪号,我们将在平均尝试 40 次后生成一个重复的随机数。
如果我们将其增加到 12 位,则平均需要 130 万次尝试来生成一个重复的随机数。
计算生成重复随机数达到预定义限制平均需要多少次尝试的更通用公式是什么?
根据经验,我可以使用这段代码来解决这个问题,但我正在寻找一个更通用的解决方案:
/**
* Calculates the average iteration at which we will generate
* a random integer that has been generated before.
* This numbers is much smaller than expected due to birthday paradox.
*/
// Generate random numbers up to (exclusive) this number:
const RANGE = 1000000000000;
let foundCollisions = 0;
const foundAt = [];
while(true) {
let i = 0;
const exists = {}
while(true) {
i++;
const random = Math.floor(Math.random() * RANGE);
if (exists[random]) {
// We found a duplicate number:
break;
} else {
exists[random] = true;
}
}
foundCollisions++;
foundAt.push(i);
// Calculate the average iteration at which we found a duplicate number:
const averageFoundAt = foundAt.reduce((total, num) => total + num) / foundCollisions;
console.log(`Found ${foundCollisions} collisions, average at ${Math.round(averageFoundAt)}th iteration.`);
}