//------------------------------------------------------------------------------- // SudokuSolutionTest.java author: Aaron Logan, 25 October 2006 // This is a possible solution for program #4 from midterm #2 for ComS 207, F06. //------------------------------------------------------------------------------- public class Program4_v2 { public static void main(String[] args) { int[][] S = {{1,2,3,4,5,6,7,8,9}, {4,5,6,7,8,9,1,2,3}, {7,8,9,1,2,3,4,5,6}, {2,1,4,3,6,5,8,9,7}, {3,6,5,8,9,7,2,1,4}, {8,9,7,2,1,4,3,6,5}, {5,3,1,6,4,2,9,7,8}, {6,4,2,9,7,8,5,3,1}, {9,7,8,5,3,1,6,4,2}}; if (gridTest(S)) System.out.println("That is a valid su-do-ku solution!"); else System.out.println("That is NOT a valid su-do-ku solution."); int[][] S1 = {{1,2,3,4,5,6,7,8,9}, {2,3,4,5,6,7,8,9,1}, {3,4,5,6,7,8,9,1,2}, {4,5,6,7,8,9,1,2,3}, {5,6,7,8,9,1,2,3,4}, {6,7,8,9,1,2,3,4,5}, {7,8,9,1,2,3,4,5,6}, {8,9,1,2,3,4,5,6,7}, {9,1,2,3,4,5,6,7,8}}; if (gridTest(S1)) System.out.println("That is a valid su-do-ku solution!"); else System.out.println("That is NOT a valid su-do-ku solution."); } //---------------------------------------------------------------------------- // gridTest method: // This method determines if the given su-do-ku puzzle solution, which is // passed to the method as a 9x9 array, is valid. A solution is valid if each // of the digits 1-9 are located in each // 1) row // 2) column // 3) 3x3 subgrid // without repetition. //---------------------------------------------------------------------------- public static boolean gridTest(int[][] array) { boolean pass = true; int i, j, a, b, z, currentDigit; int[] rowTally = {0,0,0,0,0,0,0,0,0}, colTally = {0,0,0,0,0,0,0,0,0}, sqrTally = {0,0,0,0,0,0,0,0,0}; for (i=0; i<9 && pass; i++){ for (j=0; j<9 && pass; j++){ /* Tally the number of occurences of each digit in each row */ rowTally[array[i][j]-1]++; /* Tally the number of occrrences of each digit in each column */ colTally[array[j][i]-1]++; /* If more than one occurence of a digit is found within a row or a column, then the given su-do-ku solution is invalid. */ if (rowTally[array[i][j]-1] > 1 || colTally[array[j][i]-1] > 1) pass = false; } /* Re-zero the digit-tally arrays */ for (z=0; z<9 && pass; z++){ rowTally[z] = 0; colTally[z] = 0; } } /* This loop controls the horizontal subgrid number */ for (a=0; a<3 && pass; a++) /* This loop controls the vertical subgrid number */ for (b=0; b<3 && pass; b++){ /* This loop cycles through the rows in the block */ for (i=0; i<3 && pass; i++) /* This loop cycles through the columns in the block */ for (j=0; j<3 && pass; j++){ /* Tally the number of occrrences of each digit in each block */ currentDigit = array[3*a + i][3*b + j]; sqrTally[currentDigit - 1]++; /* If more than one occurence of a digit is found within the block, then the given su-do-ku solution is invalid. */ if (sqrTally[currentDigit - 1] > 1) pass = false; } /* Re-zereo the digit-tally array */ for (z=0; z<9 && pass; z++) sqrTally[z] = 0; } return pass; } }