我正在尝试使用 Javascript 构建扫雷器。为此,我需要一个函数来返回一个“单元格”数组,然后我可以将其用作 ID 以声明为“已开采”。它最终应该看起来像这样:["cell-4-27", "cell-14-18", "cell-9-13", ...]。第一个随机数是单元格所在的行,第二个随机数是列。只有 16 行和 30 列,这就是数字的原因。
数组的长度必须为 99,并且不包含任何重复项。但是,此函数纯粹由于随机性而返回一些重复值。我试过删除重复项,但这会减少板上的地雷数量。
我怎样才能使“minedCells”的值不重复地被推送到数字 99?
function assignMines() {
let randoms = {
rows: [],
columns: []
};
let minedCells = [];
for (let i = 0; i < 99; i++) {
randoms.rows.push(Math.floor((Math.random() * 16) + 1));
randoms.columns.push(Math.floor((Math.random() * 30) + 1));
minedCells.push("cell-" + randoms.rows[i] + "-" + randoms.columns[i])
}
return minedCells;
}
最佳答案
你可以在推送之前检查该值是否已经在数组中:
function assignMines() {
let randoms = {
rows: [],
columns: []
};
let minedCells = [];
for (let i = 0; i < 99; i++) {
let el = "cell-" + Math.floor((Math.random() * 16) + 1) + "-" + Math.floor((Math.random() * 30) + 1);
if (minedCells.includes(el)) {
i--;
} else {
minedCells.push(el);
}
}
console.log(minedCells);
}
assignMines();
关于javascript - 我怎样才能确保这个函数将返回一个没有任何重复的数组,并且不会减少元素的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58121723/