亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在2D陣列中選擇三個隨機點?

如何在2D陣列中選擇三個隨機點?

三國紛爭 2022-09-28 16:34:32
我有一些代碼可以創建一個2D布爾數組,隨機選擇3個空格并將它們分配給true?,F在,我的代碼可能會選擇 2 個相同的空格并將其分配給 true,因此我可能不會最終得到 3 個空格為 true。如何更改代碼以從數組中選擇 3 個隨機且唯一的空格?boolean mineLocations[][] = new boolean[rows][cols];int rRow = random.nextInt(rows);int rCol = random.nextInt(cols);mineLocations[rRow][rCol] = true;rRow = random.nextInt(rows);rCol = random.nextInt(cols);mineLocations[rRow][rCol] = true;rRow = random.nextInt(rows);rCol = random.nextInt(cols);mineLocations[rRow][rCol] = true;
查看完整描述

3 回答

?
哆啦的時光機

TA貢獻1779條經驗 獲得超6個贊

下面是一個如何執行此操作的示例:


boolean mineLocations[][] = new boolean[rows][cols];

Random random = new Random();


int counter = 0;

while (counter < 3) { //looping while 3 distinct cells are not set to true

    int rRow = random.nextInt(rows);

    int rCol = random.nextInt(cols);


    if (!mineLocations[rRow][rCol]) {

        mineLocations[rRow][rCol] = true;

        counter++; //increasing the counter only when a new cell is set to true

    }

}

邏輯很簡單:在每次迭代時,您都會生成一個新坐標。然后檢查此坐標處的值是否仍為 false(尚未更改)。如果是,請將其設置為 true。


重復N次。


查看完整回答
反對 回復 2022-09-28
?
慕尼黑5688855

TA貢獻1848條經驗 獲得超2個贊

這是一個使用隨機和內聯流/用于緩存的解決方案


boolean mineLocations[][] = new boolean[rows][cols];


int count = rows * cols;

new Random().ints(3, 0, rows * cols - 1).forEach( rand -> {

  int y = rand / rows;

  int x = rand % cols;

  mineLocations[x][y] = true;

});


查看完整回答
反對 回復 2022-09-28
?
白衣染霜花

TA貢獻1796條經驗 獲得超10個贊

如何創建一個單獨的方法來設置初始隨機采礦位置?


例如:


import java.util.Arrays;

import java.util.Random;


class Main {

  public static void main(String[] args) {

    int rows = 3, cols = 4;

    boolean mineLocations[][] = new boolean[rows][cols];

    System.out.println(Arrays.deepToString(mineLocations));

    placeMines(3, mineLocations);

    System.out.println(Arrays.deepToString(mineLocations));

  }


  private static void placeMines(int numMines, boolean mineLocations[][]) {

    int n = mineLocations.length;

    int m = mineLocations[0].length;

    if (numMines > n * m) {

      System.err.println("Can't place more mines than slots avalaible on the grid!");

      return;

    }

    int minesPlaced = 0;

    while (minesPlaced != numMines) {

      int randomRow = new Random().nextInt(n);

      int randomCol = new Random().nextInt(m);

      if (!mineLocations[randomRow][randomCol]) {

        mineLocations[randomRow][randomCol] = true;

        minesPlaced++;

      }

    }

    return;

  }

}

輸出示例:


[[false, false, false, false], [false,false, false, false], [false, false, false, false]]

[[false, false, false, true], [false, true, false, false], [false, true, false, false]]


查看完整回答
反對 回復 2022-09-28
  • 3 回答
  • 0 關注
  • 163 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號