[英]Counting the number of times an element occurs in a given column for a 2D array?
這是數獨游戲的一種方法。
有人可以為此解釋他們的思維過程嗎? :(我很難解決這個問題。我知道第一種方法,我們應該使用for循環之類的東西。我知道我的方法的迭代是錯誤的...抱歉:(
private int countOccurrencesInCol(int col, int d){
for (int i = 0; i < grid.length; i++;){
for(int j = col; j = col; j++;){
if (grid[i][j] == d){
count++;
}
}
}
return count;
}
此方法返回數字在9 X 9矩陣的給定列中出現的次數。
private int countPossiblePlacementsInCol (int col, int d){
該方法應確定給定列中可以放置給定數字的點的數量,並返回給定列中可以在位放置數字的點的數量。 如果數字已經出現,則該方法返回0。
這是一些帶有解釋的代碼,可以幫助您了解所需的方法:
private int countOccurrencesInCol(int col, int d) {
// counter variable to count the number of occurrences
int counter = 0;
// matrix is the 2D array, the first index is the row, second is the column
// loop through each index of the given column, checking for the digit, d
for(int row = 0; row < matrix.length; row++) {
// if a match is found...
if(matrix[row][col] == d) {
// increment the counter by one
counter++;
}
}
// return the final count
return counter;
}
下一個方法比較棘手,因為我不清楚要求什么。 這種方法是否應該只返回給定列中的空單元格數量? 還是應該考慮數獨的所有規則並檢查那些空單元格對於該數字是否有效? 如果是前者,則解決方案很簡單:
private int countPossiblePlacementsInCol(int col, int d) {
// I am assuming an empty cell is indicated by 0. In that case,
// we can reuse the previous method to find the number of occurrences of d,
// and the occurences of 0
// first, find out if the digit already occurs in the row, return 0
// if it does:
if(countOccurrencesInCol(col, d) > 0) {
return 0;
}
// next, return the number of times 0 occurs (the number of empty cells):
return countOccurrencesInCol(col, 0);
}
但是,如果您必須僅計算有效步數,則將變得更加棘手。 上一個方法的最后一行將變成類似以下內容:
private int countPossiblePlacementsInCol(int col, int d) {
//start the same as the previous method:
if(countOccurrencesInCol(col, d) > 0) {
return 0;
}
int counter = 0;
// this time, for each cell in the column, you must check that it is a valid move:
for(int row = 0; row < matrix.length; row++) {
if(countOccurrencesInRow(row, d) == 0 &&
countOccurencesInSquare(row, col, d) == 0) {
counter++
}
}
}
我這次使用的兩個方法countOccurrencesInRow
和countOccurencesInSquare
將執行類似於countOccurrencesInCol
。 該Row
一個是基本相同的Col
之一,但它會檢查的行,而不是一列。 Square
一號有點棘手。 假設您知道數獨的規則,那么您應該知道一個正方形是9x9游戲板的3x3部分(其中有9個3x3部分)。 Square
方法將使用row和col找出給定單元格所在的正方形,然后遍歷該正方形的行和列,計算給定數字的出現次數。 為此,您將需要使用兩個for循環,一個嵌套在另一個循環中。 如果您在理解如何正確使用循環以及遍歷數組時遇到麻煩,那么我建議您與您的老師/教授聯系,以獲取有關該主題的更多幫助。
希望這些說明和示例對您有所幫助。 祝好運。
您不需要第二個for循環。
列中出現數字的計數可以通過
private int countOccurrencesInCol(int col, int d){
for (int i = 0; i < grid.length; i++){
if (grid[i][col] == d){
count++;
}
}
return count;
}
希望這可以幫助!
祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.