I have a Sudoku puzzle and I need to make sure that each row and column have each number 1 through 9. What is the easiest way of doing this? The code snippet that I have so far is below.

public static boolean rowsAreValid(int[][] array){
        for(int i = 0; i < array.length; i++){
            for (int j=0;j<array.length;j++){

This is my Sudoku puzzle. Note that I also need to do the same for each 3x3 section. Your help is greatly appreciated!

3 8 4 2 1 6 9 7 5 
9 7 1 8 5 4 3 2 6 
5 2 6 7 9 3 4 8 1 
2 5 9 6 3 7 8 1 4 
1 3 8 4 2 9 6 5 7 
6 4 7 5 8 1 2 3 9 
8 1 3 9 4 5 7 6 2 
7 9 5 3 6 2 1 4 8 
4 6 2 1 7 8 5 9 3

Edited 3 Years Ago by Dani: Formatting fixed

One way is to sum all the numbers of the row/column/section. If the sum is 45, it's probably correct.

A second way could be to put all the numbers in an priorityqueue and compare that Q with another control Q that you made.

For ex,

Q 1: // Control Q
[1][2][3][4][5][6][7][8][9]

Now, fill the second Q with your numbers, as it's an PriorityQ it will selfsort.
So now you just compare Q1 and Q2.

If they match, you got all the numbers required.

P.s. your choice of topic is a bit misleading, as you don't want to do any sorting, just control ;)
D.s.

One way is to sum all the numbers of the row/column/section. If the sum is 45, it's probably correct.

Unfortunately that's nowhere near sensitive enough - eg the sum of nine fives is also 45. But it does inspire an idea for an improved version...
how about summing the squares of the nine numbers? I don't have the math to prove it, but I strongly suspect there's only one way to add nine perfect squares to give 285

Edited 4 Years Ago by JamesCherrill: n/a

Unfortunately that's nowhere near sensitive enough - eg the sum of nine fives is also 45. But it does inspire an idea for an improved version...
how about summing the squares of the nine numbers? I don't have the math to prove it, but I strongly suspect there's only one way to add nine perfect squares to give 285

Hehe yeah, you're right. Though the probability of getting 9x9 in a row/column/section is quite high :-)
But I admit, there's much better ways :-)

Since you are just looking for an algorithm for testing...
Set up an Array [10] and set all of the values to 0.
Traverse your row/column/3x3 taking your "found" value as the index, and set the value at THAT index to 1.
Total your Array [1..9].
If correct, your answer will be 9.
If you have less than 9, there is a number (or an index, for your purposes) missing.
Be sure to reset your Array to 0s between each iteration.

Edited 4 Years Ago by hfx642: n/a

This article has been dead for over six months. Start a new discussion instead.