javascript - 返回 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, 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));
推荐阅读
- r - 使用 imp4p 包 impute.slsa 函数的缺失值插补错误:fast_apply_sd_na_rm_T(xincomplete1, 1) 中的错误:不是矩阵
- javascript - Cypress:Cypress 自定义命令的返回值实际上在测试文件中返回 null
- java - 在 Jsoup 中解析 html
- ios - PDFKit 和 PDFDocument 注释在 Adobe Acrobat 中不可见
- laravel - 如何使用 vagrant box 修复流明迁移错误
- android - 应用程序在打开 QR Scanner Flutter 时崩溃
- alfresco - 拥有对文档的访客访问权限 - 这是否应该允许用户搜索此文档?
- angular - 我想在 React 表单输入中显示 A$,但只返回数字;
- bash - 如何在 Expect 脚本中循环 Bash 数组
- python - 在 python 中处理大型 JSON 数据