简体   繁体   中英

Sudoku - java. I am trying to see if my row is complete or not. it cannot have a number repeated

I have been working on this code for a while and i am stuck on this code. I am not sure what i am doing wrong. If someone could point me on the right direction

this is what i need to code followed by the code below it :

 /**
 * This method determines whether the ints 1-9 are present exactly
 * once in each column.  Sets valSeen[i] = 1 if it sees i.  If at any
 * point valSeen[i] is already 1, the rows are not complete because of 
 * duplicate entries.  
 * 
 * If game[x][y] == -1, there is a blank entry so the row cannot be complete.
 * 
 * @param valSeen: an array of ints that serve as flags to indicate whether
 *                 their entry has been seen before or not.
 * 
 * returns: true if each digit 1-9 is present in the column exactly once, else false
 **/

public boolean rowsComplete(int[] valSeen)
    {   
    // Write the appropriate nested loops to check the rows.
    int temp = 0;
    boolean val = false;         
    for(int i = 0; i < SIZE; i++) {        //row [i]
        for(int j = 0; j < SIZE; j++) {    //columns [j]

            temp = game[i][j];

            if( temp != -1) {                //make sure the index of the row is not empty

                if(valSeen[temp] != 1) {     //make sure the number was not previously                        

                    valSeen[temp] = 1;
                    val = true;
                }

                else {
                   val = false;
                }

            }

            else
              val = false;

        }

        setZero(valSeen);     //sets all the indexes of valseen to zero aFter each row

    }


    // Remember to reset valSeen to 0 after each row.

    return val; // Change this, placeholder so your code will compile
}

As noted in the other answer, you might have the indexing into your flag array wrong, because of java's zero-based indexing.

But there are other problems with the code as it is.

If the last row is valid, your method will return true based on its validity, regardless of having seen an invalid row earlier.

You would do better to set the result true before the loop, change it to false as appropriate, and never set it true again.

Maybe you are going out of boundaries with the variable temp. try setting

temp = game[i][j] - 1

Normally your numbers will be from 1 to 9 in game[][] so temp will also receive 1 to 9 and then you enter an array of size 9 to index 9, but you need to remember the count starts from zero so you actually want index 8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM