2016-02-20 57 views
0

所以,現在我有一個2D數組,它根據用戶輸入(行和列)打印遊戲字段。它用'.'字符填充陣列。我現在需要的是使用第三個用戶輸入amountTreasure來確定地圖上寶物的數量。在隨機位置填充固定數量珍寶的2D字符數組

我該如何循環這個二維數組,並在隨機位置放置3個寶物。有趣的部分是我需要防止計算機多次隨機選擇相同的地方。

我現在有這段代碼。

public static char[][] createMatrix(int n, int m, int amountTreasure) { 


    Random rand = new Random(); 
     char[][] matrix = new char[n][m]; 
     for (char[] matrixList : matrix) { 
      Arrays.fill(matrixList, '.'); 
     } 
     for (int v = 0; v < matrix.length; v++) { //Loop through matrix 
      for (int b = 0; b < matrix[v].length; b++) { 
       continue; 
      } 
     } 
     return matrix; 
    } 

我想是這樣

matrix[v][b] = (char) rand.nextInt('X') 

,但它不工作。我對Java真的很陌生,不知道該怎麼做。

回答

1

不是循環遍歷數組,而是讓您的Random返回寶藏應該去的座標。那麼你只需要檢查是否意外地產生了相同的座標。

Random random = new Random(); 

for (int i = 0; i < amountTreasure; i++) { 
    int treasureX, treasureY; 

    do { 
     treasureX = random.nextInt(n); 
     treasureY = random.nextInt(m); 
    } while (matrix[treasureX][treasureY] == 'X'); 

    matrix[treasureX][treasureY] = 'X'; 
} 
+0

這是行得通的,但問題是電腦可能會多次選擇相同的地方,這樣寶物的數量就會少於需要的數量。 – Moontego

+1

不,它不會多次選擇相同的地方。如果它選擇'X',那麼它會嘗試選擇另一個隨機的。這就是他使用do-while()循環的原因。 – mkabanen

+0

現在我明白了,謝謝 – Moontego

2

不是循環遍歷數組,而是計算隨機位置並將寶藏放在那裏。

for(int tresasure = 0; treasure < amountTreasure; treasure++) { 
    int x, y; 
    do { 
     x = random.nextInt(matrix.length); 
     y = random.nextInt(matrix[x].length); 
    } while(matrix[x][y] == 'X'); 
    matrix[x][y] = 'X'; 
} 
+0

他明確表示他不想多次選擇一個單元格。這可能發生在您的解決方案中。 – mkabanen

+0

是的,我更正了我的答案 – loonytune

+0

得承認,我現在喜歡你的答案! – Thomas

1

這是通過使用HashSet來防止重複的方法之一。它不循環矩陣來選擇隨機位置。

這是代碼片段:

public static char[][] createMatrix(int n, int m, int amountTreasure) { 
    Random rand = new Random(); 
    char[][] matrix = new char[n][m]; 
    for (char[] matrixList : matrix) { 
     Arrays.fill(matrixList, '.'); 
    } 

    Set<String> hashSet = new HashSet<>(); 
    /* Select At Random */ 
    for(int iter = 0; iter < amountTreasure; iter++) { 
     String trs = null; 
     int randRow = -1; 
     int randCol = -1; 
     /* Generate New Random */ 
     while(!hashSet.contains(trs) && trs == null) { 
      randRow = rand.nextInt(n); 
      randCol = rand.nextInt(m); 
      trs = new String(String.valueOf(n) + "," + String.valueOf(m)); 
     } 
     /* Add In HashSet */ 
     hashSet.add(trs); 
     matrix[randRow][randCol] = 'X'; 
    } 
    /* Return Matrix */ 
    return matrix; 
} 

輸出:

. . . . 
. . X . 
X . X . 
. . . . 
1

您可以瀏覽您的二維陣列並保存「空」的細胞在另一個列表中的位置,然後從隨機選擇他們。這樣你就不能多次選擇一個單元格。

如何保存單元格位置? 你可以賺更多的類細胞:

class Cell { 
     int x, y; 
     public Cell(int x, y) { 
      this.x = x; 
      this.y = y; 
     } 
} 

然後讓細胞的ArrayList:

List<Cell> emptyCells = new ArrayList<Cell>(); 

翻檢二維數組,並添加空單元有:

for (int v = 0; v < matrix.length; v++) { //Loop through matrix 
    for (int b = 0; b < matrix[v].length; b++) { 
     if(matrix[v][b] == '.') emptyCells.add(new Cell(v, b)); 
    } 
} 

現在你可以從那些隨機選擇。