[英]Filling a 2D array with randomised numbers
我已經開始嘗試創建Ken Ken拼圖。 如果你不確定Ken Ken是什么,它就像Sudoku一樣,行或列中沒有重復的整數值。
我正在嘗試使用為每個新行創建的數組列表中的數字填充2D數組。 我進行檢查以查看從數組列表中獲取的數字是否與其自己的行和列中的任何數字都不匹配。
當我運行我的代碼時,當我嘗試從列表中刪除整數值時,我得到一個“Index Out Of Bounds”異常。 我不確定為什么會這樣,因為我認為我得到了正確的元素。
這是我的代碼:
int GRID_SIZE = 4;
int[][] grid = new int[GRID_SIZE][GRID_SIZE];
List<Integer> nums = new ArrayList<Integer>();
private void populateGrid() {
for (int row = 0; row < GRID_SIZE; row ++) {
// Creates an array of values from 1 to grid size.
for (int i = 1; i <= GRID_SIZE; i++) nums.add(i);
for (int col = 0; col < GRID_SIZE; col++) {
while (nums.size() > 0) {
// Gets a random number from the Array List
int ranNum = nums.get(numGen.nextInt(GRID_SIZE));
// Checks to see if the number is placeable.
if (canPlace(ranNum, row, col)) {
// Places the number in the 2D Array
grid[row][col] = ranNum;
break;
} else {
// Removes duplicate element from the Array List.
nums.remove(ranNum); <------{Index Out Of Bounds Exception]
}
}
}
}
}
private boolean canPlace(int ranNum, int row, int col) {
for (int i = 0; i < GRID_SIZE; i++) {
// Checks if the specified number is already in the row/column.
if (grid[col][i] == ranNum) return false;
if (grid[i][row] == ranNum) return false;
}
return true;
}
我有幾個問題:
首先, 為什么我得到的錯誤是我 ?
其次,對於網格和我放置數字的方式,有什么比2D數組更好用嗎?
最后, 我正確使用了休息嗎?
提前感謝您的回答。
由於List
API中的失敗(IMO)而發生IndexOutOFBoundsException
。 它有一個remove(Object element)
方法,它是你想要調用的方法,還有一個remove(int index)
方法,這是你實際調用的方法。 后者試圖刪除給定索引處的元素,因為您的參數可能大於列表大小。 您可以將ranNum
變量ranNum
轉換為Integer
或Object
,以確保調用正確的方法。
for (int i = 0; i <= GRID_SIZE; i++) nums.add(i);
這對我來說沒什么意義。 你正在添加0-4的數字。 數組中只有索引最多3個。 0-1-2-3 ...
沒有真正看到更多的代碼,或者確切地知道你的索引在哪里超出界限......這是一個黑暗的鏡頭。
如何解決問題的方法呢? 從有效的方塊開始並對其進行轉換。 這兩個操作“交換兩行”和“交換兩列”保留了廣場的屬性。 這允許你做兩個Fisher-Yates shuffle,一個在行上,一個在列上,只要你從一個有效的方塊開始就可以給你一個有效的隨機方塊。 構造一個初始有效方是微不足道的:
123456
234561
345612
456123
561234
612345
在仔細查看我的代碼后,我意識到我的主要錯誤是使用canPlace(int ranNum, int row, int col)
方法。
我所做的就是交換col
和row
值並且它有效。
感謝大家的幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.