So, I asked a question 2 days ago, I’m going to try to rework it to make it simpler:
I have a 2D array, which represents a Sudoku game.
I’m trying to check the game for errors as with a typical Sudoku game:
No number (1-9) is repeated within a row, column or 3×3 square. No empty cells.
The user IS ALLOWED to enter a repeat value, but the game will not be considered “won” until they fix these errors. I want to allow them to enter wrong values, just not win.
I’m very new to Java, so I had a limited knowledge to approach this with. I was going to try a long if, else statement comparing all the cells. That didn’t work, because -1 was repeated. (-1 represents an empty square). I tried to get around this, but realized that this if statement was too messy and there had to be a better way.
Then I thought to use boolean statements to test each number, setting to true if it had been seen before. That seems messy with so many boolean statements.
So, I’m kind of at a wall. Any tips on what to try? Try not to use anything advance, only been doing Java 2 months.
1) You want to loop through the values, such as with a for loop. That will be much better than a long if-else-if chain.
2) To keep track of values seen, a simple way for you would probably be to use a list. I’ll try to keep this example as simple as possible since you ask for “nothing advance.”
This will return true if row
rowNumberhas a number repeat in the 2D array specified bysudokuArray, and false otherwise. Notice thesudokuArray != -1, that takes into account the -1 placeholder for empty squares that you mentioned.When you compile something like this, if the compiler errors about trying to put an integer into the array list, you might have to make it generic by specifying
ArrayList<Integer>. I do not recall if Java will auto-box a primitive for you when you specify a destination of type Object.This then leads into a small side-lesson which might be beneficial to you since you are new: Java has both primitive types (boolean, byte, short, int, long, float, double) and object versions of the primitive types (Boolean, Byte, Integer, etc.). If you do
int i = 0;andInteger i2 = i;, Java will be nice enough to do the conversion for you.checkColumnwould be very similar.check3X3area(or whatever you would want to call it) could be somewhat similar; perhaps you could use 2 for-loops, one nested inside the other, and loop 3 times each instead of 9. This will be left as an exercise for you.Also, you could make this generic to allow for sudoku boards that are not of size 9 with a few modifications.