簡體   English   中英

如果沒有確定的編號,如何驗證數組並添加編號?

[英]How to verify array and add number if not certain number?

我認為標題可能會聽起來比實際容易。

基本上我必須檢查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)的構造函數創建,如果它具有0 ,它將返回false,因為它沒有被表示為空單元格。 任何幫助表示贊賞,謝謝

您應該先檢查a[i]是否為空:

更改

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

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

這利用了&& (AND)運算符是短路運算符的優勢-如果第一個(左)操作數為false ,則不計算第二個(右)操作數,因此將僅計算vals[a[i]] > 0如果a[i]包含非空值。

您還必須在增加計數器之前添加范圍檢查:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM