我認爲標題可能會讓它聽起來更容易。如何驗證數組並添加數字(如果不是某個數字)?
基本上我必須檢查一個2d suduko數組是否有效。
public class Sudoku{
//The n x m grid that defines the Sudoku
private int[][] theGrid;
//the number that defines the empty cell
private int empty;
//constructor
public Sudoku(int[][] g){
theGrid = g;
}
//secondary constructor, where e represents the empty cell
public Sudoku(int[][] g, int e){
theGrid = g;
empty = e;
}
public boolean isValid(){
//checks each row, column and sub box inside
}
下面的函數被調用每行,列和副箱,將上述到一個數組,以確保sudkou的各個方面是有效的之後。
public boolean checkValues(int[] a){
int[] vals = new int[a.length + 1];
for (int i = 0; i < a.length; i++){
//number out of range and not empty cell
if ((a[i] < 1 || a[i] > a.length) && a[i]!=empty)
return false;
//duplicate number and not empty cell
if (vals[a[i]] > 0 && a[i]!=empty)
return false;
//mark number as used
vals[a[i]]++;
}
return true;
}
現在繼承問題。如果使用-1或10(或其範圍外的任何數字)創建數獨網格作爲空單元格,它會返回arrayindexoutofbounds異常。我假設vals[a[i]]++
是試圖添加一個不存在的數字的罪魁禍首。那麼如何解決這個問題,它只會增加數字,如果它不是一個空單元?我試過
if(a[i]!=empty)
vals[a[i]]++;
但它給了我同樣的錯誤。
我本來
//secondary constructor, where e represents the empty cell
public Sudoku(int[][] g, int e){
for(int i = 0; i < g.length; i++){
for (int j = 0; j < g[0].length; j++){
//for every instance of empty cell e, change to specific value
if(g[i][j] == e){
g[i][j] = 0;
}
}
}
theGrid = g;
}
這將迫使每一個空單元格爲0,並在checkValues
有a[i]!=0
代替a[i]!=empty
,但改變它,因爲其中一個獨用-1
爲空創建一個測試細胞,但它實際上有0
在裏面。所以它應該返回false,但是返回true。
另外,有沒有辦法讓它如此創建使用只有1參數sudoku(int[][] g)
的構造函數,它會返回false,如果它有0
,因爲它沒有被表示爲一個空單元格。感謝任何幫助,感謝
「如果您使用-1或10的數獨格」爲什麼你認爲你要做到這一點?這顯然不是一個有效的數獨! –
@JoeC使用-1或10作爲空單元格 –
啊。我可以向你推薦['OptionalInt'](https://docs.oracle.com/javase/8/docs/api/java/util/OptionalInt.html)類嗎? –