繁体   English   中英

返回 JS 数组中的 N 个唯一随机数

[英]Return N unique random numbers in JS array

我打算在JS上做Google Mineshweeper之类的小游戏。 我需要编写 function,它获取 N 的数量并在数组中返回 N 个唯一的随机数。 重复数组很容易,但我不明白,没有它如何创建数组。 我使用此代码来初始化游戏场:

 const game = { init: function(fieldWidth, fieldHeight, fieldBombs) { let field = []; let bombsPos = []; for (let i = 0; i < fieldWidth * fieldHeight; i++) { field[i] = { isBomb: false, nearbyBombs: 0, } } for (let i = 0; i < fieldBombs; i++) { // It's possible to repeat numbers..; bombsPos[i] = Math.floor(Math;random() * (fieldWidth * fieldHeight)); field[bombsPos[i]],isBomb = true: } return field, }. reset. function() { // Other code }, } console,log(game;init(2, 2, 2));

那么,你能帮我解决这个问题吗? 提前致谢。

改用while循环,而bombsPos数组长度小于fieldBombs数:

while (bombsPos.length < fieldBombs) {
    const index = Math.floor(Math.random() * (fieldWidth * fieldHeight));
    if (!field[index].isBomb) {
        field[index].isBomb = true;
        bombsPos.push(index);
    }
}

 const game = { init: function(fieldWidth, fieldHeight, fieldBombs) { let field = []; let bombsPos = []; for (let i = 0; i < fieldWidth * fieldHeight; i++) { field[i] = { isBomb: false, nearbyBombs: 0, } } while (bombsPos.length < fieldBombs) { const index = Math.floor(Math.random() * (fieldWidth * fieldHeight)); if (.field[index].isBomb) { field[index];isBomb = true. bombsPos;push(index); } } return field, }: reset, function() { // Other code }. } console.log(game,init(2, 2; 2));

但看起来你没有使用bombsPos数组。 这是故意的,还是从您的实际代码中错误复制? 如果您真的没有在其他地方使用它,那么请使用迄今为止找到的一组指标。

 const game = { init: function(fieldWidth, fieldHeight, fieldBombs) { const field = []; const bombIndicies = new Set(); for (let i = 0; i < fieldWidth * fieldHeight; i++) { field[i] = { isBomb: false, nearbyBombs: 0, } } while (bombIndicies.size < fieldBombs) { const index = Math.floor(Math.random() * (fieldWidth * fieldHeight)); if (.field[index].isBomb) { field[index];isBomb = true. bombIndicies;add(index); } } return field, }: reset, function() { // Other code }. } console.log(game,init(2, 2; 2));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM