Hi all - this is the code:
package sodukupackage;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class ReadSudokuValuesIntoArray {
public static void main(String[] args){
int[][] sudoku = new int[9][9];
Scanner sc = null;
try{
int i = 0, j = 0, count = 1;
sc = new Scanner(new File("validsudoku.txt"));
while (sc.hasNextInt()){
if((count % 9) == 0){
sudoku[i][j] = sc.nextInt();
count++;
i++;
j = 0;
} else {
sudoku[i][j++] = sc.nextInt();
count++;
}
}
}
catch (FileNotFoundException fnfe){
System.out.println("File not found.");
System.exit(1);
}
finally {
sc.close();
}
printArray(sudoku);
rowsAreValid(sudoku);
columnsAreValid(sudoku);
regionsAreValid(sudoku);
}
public static void printArray(int[][] array){
for(int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
public static boolean rowsAreValid(int[][] array){
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
for (int column = 0; column < array.length; column++){
if (column != j && array[i][column] == array[i][j]){
return false;
}
}
}
}
return true;
}
public static boolean columnsAreValid(int[][] array){
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
for(int row = 0; row < array.length; row++){
if (row != i && array[row][j] == array[i][j]){
return false;
}
}
}
}
return true;
}
public static boolean regionsAreValid(int[][] array){
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
for (int row = (i/3) * 3; row < ( i / 3) * 3 + 3; row++){
for(int column = (j / 3) * 3; column < (j / 3) * 3 + 3; column++){
if (row != i && column != j && array[row][column] == array[i][j]){
return false;
}
}
}
}
}
return true;
}
}
My rowsAreValid and columns are valid methods work perfectly, but for some reason I can't quite figure out why my regionsareValid method won't work. I've tried changing numbers in the Sudoku puzzle to make it invalid, but the reigion checker always returns true even if it's false.
We read in a file that contains this:
5 9 3 1 7 8 6 4 2
1 8 2 6 3 4 9 7 5
6 7 4 9 2 5 8 1 3
3 2 1 4 5 9 7 6 8
8 4 5 3 6 7 2 9 1
9 6 7 8 1 2 5 3 4
7 1 6 2 8 3 4 5 9
2 5 9 7 4 1 3 8 6
4 3 8 5 9 6 1 2 7