簡體   English   中英

Java:如何隨機選擇兩個相鄰的值

[英]Java: How to choose two near each other values randomly

我有一個 function 可以將所有坐標打印到一個列表( col 和 row )中,其中我有 0 的網格,但是,我想對其進行處理並使用它來隨機選擇一個生成位置 1。我該怎么做? 至於我,列表中的 output 看起來確實很亂。

代碼:

  public static void addNewNum(int[][]grid) {
        List freeSpace = new ArrayList();
        for(int row=0; row< grid.length; row++)  {
            for(int col=0; col< grid[row].length; col++) {
                if (grid[row][col] ==0) {
                    freeSpace.add(col);
                    freeSpace.add(row);
                }
        
            }
            System.out.println(Arrays.toString(freeSpace.toArray()));
         }
     }
    

作為 output 我有:

  1   2   3   4   
  ================
 1| 0 | 0 | 0 | 0 | 
   --+---+---+--
 2| 0 | 0 | 0 | 0 | 
   --+---+---+--
 3| 0 | 0 | 0 | 0 | 
   --+---+---+--
 4| 0 | 0 | 0 | 0 | 
  ================
[0, 0, 1, 0, 2, 0, 3, 0]
[0, 0, 1, 0, 2, 0, 3, 0, 0, 1, 1, 1, 2, 1, 3, 1]
[0, 0, 1, 0, 2, 0, 3, 0, 0, 1, 1, 1, 2, 1, 3, 1, 0, 2, 1, 2, 2, 2, 3, 2]
[0, 0, 1, 0, 2, 0, 3, 0, 0, 1, 1, 1, 2, 1, 3, 1, 0, 2, 1, 2, 2, 2, 3, 2, 0, 3, 1, 3, 2, 3, 3, 3]

列表以 col1,row1,col2,row2,col3,row3 的格式打印...而且我需要以某種方式隨機選擇彼此靠近的值,這樣它們就像一個有效的坐標(我不能選擇 col1,col2 或 row2,col3)也許它做得更容易,我應該創建其他列表,但那是我想出的列表(列表的 output 看起來有點奇怪)

所以基本上它應該像

  1. 帶有坐標的生成列表
  2. 選擇正確的坐標(例如: col2,row2 )
  3. 用數組中的值 1 更改它

最好構建和使用坐標對的類型列表:

public static List<Pair<Integer, Integer>> getEmptyCells(int[][] grid) {
    List<Pair<Integer, Integer>> result = new ArrayList<>();
    for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid[i].length; j++) {
            if (0 == grid[i][j]) {
                result.add(new Pair(i, j));
            }
        }
    }
    return result;
}
// ....

List<Pair<Integer, Integer>> emptyCells = getEmptyCells(grid);

Random r = new Random();
Pair<Integer, Integer> freeCell = emptyCells.get(r.nextInt(emptyCells.size()));

grid[freeCell.getFirst()][freeCell.getSecond()];

如果對列表不是選項並且坐標表示為List<Integer>中的問題所示,則列表的大小始終是偶數,因此對列表的一半計算該對的索引,並且在[0, list.size()/2)范圍內,網格單元的坐標可以計算為: row = 2 * i; col = 2 * i + 1; row = 2 * i; col = 2 * i + 1; 如下所示:

public static List<Integer> getEmptyCellPairs(int[][] grid) {
    List<Integer> result = new ArrayList<>();
    for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid[i].length; j++) {
            if (0 == grid[i][j]) {
                result.add(i);
                result.add(j);
            }
        }
    }
    return result;
}


List<Integer> emptyCellPairs = getEmptyCellPairs(grid);

Random r = new Random();

int pairIndex = r.nextInt(emptyCellPairs.size() / 2);

// free cell
grid[2 * pairIndex][2 * pairIndex + 1];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM