954,549 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How Do I Sort A 2-Dimensional Array?

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

rupes0610
Newbie Poster
1 post since Feb 2012
Reputation Points: 10
Solved Threads: 0
 

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.

Zhoot
Light Poster
26 posts since Jan 2008
Reputation Points: 10
Solved Threads: 3
 
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 thesquares 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

JamesCherrill
Posting Genius
Moderator
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
 
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 :-)

Zhoot
Light Poster
26 posts since Jan 2008
Reputation Points: 10
Solved Threads: 3
 

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.

hfx642
Posting Pro
515 posts since Nov 2009
Reputation Points: 248
Solved Threads: 105
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: