如何解决返回 JS 数组中的 N 个唯一随机数
我打算在 JS 上做像 Google Mineshweeper 这样的小游戏。而且我需要编写函数,它获取数量 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,fieldBombs) {
const field = [];
const bombIndicies = new Set();
for (let i = 0; i < fieldWidth * fieldHeight; i++) {
field[i] = {
isBomb: false,}
}
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;
},2));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。