检查随机化的数字是否在数组中,如果为true,则再次随机化

Check if randomized number is in an array, if true then randomize again?

本文关键字:随机化 如果 true 数字 是否 数组 检查      更新时间:2023-09-26

我正在创建一个战列舰游戏,并试图随机化计算机的舰艇。然而,它有时会多次随机化同一位置,从而在某些回合中创建不到8艘船。我试图使用indexOf来修复这个问题,但无论我如何更改代码,我似乎都无法使其正常工作。如果随机化的数字在数组shipLocations中,那么我想再次滚动该数字,直到它与数组中的任何数字都不匹配。有什么想法吗?

var shipLocations = [];
function randShips() {
    for (i = 0; i < 8; i++) {
        var randomize = Math.floor(Math.random() * 64 + 1);
    if (shipLocations.indexOf(randomize) == true) {
        var randomize = Math.floor(Math.random() * 64 + 1);
    }
    else {
        shipLocations.push(randomize);    
    }
    } //end of i loop
} //end of randShips()
randShips();
console.log(shipLocations);

编辑:因此,在尝试了一些答案后,在测试了大约100次后,它似乎以应有的方式工作。

var shipLocations = [];
function randShips() {
while (shipLocations.length < 8) {
    var randomize = Math.floor(Math.random() * 64 + 1);
    while (shipLocations.indexOf(randomize) > -1) {
        randomize = Math.floor(Math.random() * 64 + 1);
    }
    shipLocations.push(randomize);
}
}
randShips();
var shipLocations = [];
function randShips() {
    while ( shipLocations.length < 8 ) {
        var randomize = Math.floor(Math.random() * 64 + 1);
        while ( shipLocations.indexOf(randomize) >= 0 ) {
            randomize = Math.floor(Math.random() * 64 + 1);            
        }
        shipLocations.push(randomize);
    }
} //end of randShips()
randShips();
console.log(shipLocations);

由于您想要8个唯一的值,很可能一行中创建的2个数字都已经在数组中了。所以我想你会想做一个while:

while (shipLocations.indexOf(randomize) != -1) {
    randomize = Math.floor(Math.random() * 64 + 1);
}

var部分不应该在那里,这只是变量的第一个实例所必需的。

在javascript中,返回值为-1的false条件。

因此,将if else条件更改为:

if (shipLocations.indexOf(randomize) != -1) { //true condition equivalent
    var randomize = Math.floor(Math.random() * 64 + 1);
}
else {
    shipLocations.push(randomize);    
}

indexOf不返回布尔值,它返回匹配元素的索引(int)。

所以代码应该是

if (~shipLocations.indexOf(randomize)) {
    var randomize = Math.floor(Math.random() * 64 + 1);
}

您可以使用此函数为数组获取一个真正的唯一数字。

function uniqueRandom( arr) {
    var num = Math.floor(Math.random() * 64 + 1);
    if (~arr.indexOf(num)) {
        uniqueRandom(arr);
    } else {
        return num;
    }
}

顺便说一句,你写的逻辑有问题。如果你发现了一个重复的数字,你只需再次将其随机化,而不将其推入数组。因此使用CCD_ 4或递归函数应该可以很好地完成这项工作。