我正在尝试使用Javascript构建Minesweeper。为此,我需要一个函数,该函数将返回“单元”的数组,然后可以将其用作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/

10-09 17:05
查看更多