2017-09-03 29 views
0

我認爲標題可能會讓它聽起來更容易。如何驗證數組並添加數字(如果不是某個數字)?

基本上我必須檢查一個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,並在checkValuesa[i]!=0代替a[i]!=empty,但改變它,因爲其中一個獨用-1爲空創建一個測試細胞,但它實際上有0在裏面。所以它應該返回false,但是返回true。

另外,有沒有辦法讓它如此創建使用只有1參數sudoku(int[][] g)的構造函數,它會返回false,如果它有0,因爲它沒有被表示爲一個空單元格。感謝任何幫助,感謝

+0

「如果您使用-1或10的數獨格」爲什麼你認爲你要做到這一點?這顯然不是一個有效的數獨! –

+0

@JoeC使用-1或10作爲空單元格 –

+0

啊。我可以向你推薦['OptionalInt'](https://docs.oracle.com/javase/8/docs/api/java/util/OptionalInt.html)類嗎? –

回答

0

您應該檢查a[i]不爲空第一:

變化

if (vals[a[i]] > 0 && a[i]!=empty) 
    return false; 

if (a[i]!=empty && vals[a[i]] > 0) 
    return false; 

這需要的&&(AND)運算的優勢是一個短路操作符 - 如果第一個(左)操作數是false,則第二個(右)操作數不被評估,所以0只有在a[i]包含非空值時纔會評估。

您還可以增加櫃檯前添加一個範圍檢查:

if (a[i]!=empty) 
    vals[a[i]]++; 
+0

不幸的是,即時通訊仍然得到相同的錯誤 –

+0

是的,這將做到這一點。男人我擁有一切,只是以不同的順序哈哈。謝謝你的幫助。 –

+0

@AlonzoRobbe不客氣! – Eran

相關問題