你的算法非常无效。当数组几乎填满时,您实际上会进行数百万次无用的迭代,直到您运气好并且 RNG 不小心选择了丢失的数字。将其重写为:
- 生成一个包含所有可能数字的数组 - 从 1 到 99。
- 当您需要随机数时,在此数组、拼接元素和此随机位置的当前边界中生成一个随机索引,将其从数组中删除并将其值用作您想要的随机数。
- 如果生成的数字不符合您的某些条件(minDiff?)将它们返回到数组。请注意,如果数组中留下的所有内容都无法满足您的条件,您仍然可以永远停滞在循环中。
以这种方式从数组中提取的每个值都保证是唯一的,因为您最初用唯一的数字填充它并在使用时将其删除。
我已经剥离了绘图并将生成的数字放入可以在控制台中检查的数组中。把你的画放回去,它应该可以工作了——现在会立即生成数字:
var snakes = ['./Images/Snakes/snake1.png','./Images/Snakes/snake2.jpg','./Images/Snakes/snake3.gif','./Images/Snakes/snake4.gif','./Images/Snakes/snake5.gif','./Images/Snakes/snake6.jpg'];
var ladders = ['./Images/Ladders/ladder1.jpg','./Images/Ladders/ladder2.jpg','./Images/Ladders/ladder3.png','./Images/Ladders/ladder4.jpg','./Images/Ladders/ladder5.png'];
function drawTable()
{
// Now generating snakes.
generateRand(snakes,0);
generateRand(ladders,1);
}
var uniqNumbers = []
for(var idx = 1; idx < 100; idx++){ uniqNumbers.push(idx) }
var results = []
function generateRand(arr,flag)
{
var valFlag = 0;
var minDiff = 8; // Minimum difference between start of snake/ladder to its end.
var temp;
for(var i = 0; i< arr.length; ++i) {
var valid = false
// This is the single place it still can hang, through with current size of arrays it is highly unlikely
do {
var random_1 = uniqNumbers.splice(Math.random() * uniqNumbers.length, 1)[0]
var random_2 = uniqNumbers.splice(Math.random() * uniqNumbers.length, 1)[0]
if (Math.abs(random_1 - random_2) < minDiff) {
// return numbers
uniqNumbers.push(random_1)
uniqNumbers.push(random_2)
} else {
valid = true
}
} while (!valid);
if(flag == 0) // Snake
{
if(random_1 < random_2) // Swapping them if the first number is smaller than the second number.
{
var temp = random_1; random_1 = random_2; random_2 = temp
}
}
else // Ladders
{
if(random_1>random_2) // Swapping them if the first number is greater than the second number.
{
var temp = random_1; random_1 = random_2; random_2 = temp
}
}
// Just for debug - look results up on console
results.push([random_1, random_2])
}
}
drawTable()