import java.util.Scanner; /** Class to verify solutions to Sudoku puzzles. Correct solutions have the numbers 1..9 in each row, column, and 9 squares of 3x3. A putative solution is read in from stdin, and yay or nay is printed out. Used as an example to illustrate 2D arrays and scanners for cs136. @author Stacia K. Wyman 2006 */ public class SudokuVerifier{ /** constant grid size: 9x9 */ public final static int SIZE = 9; /** board is a 9x9 2D array to hold the solution */ protected int board[][]; /** constructor simply allocates the array */ public SudokuVerifier(){ board = new int[SIZE][SIZE]; } /** Check row verifies each row one by one @pre board contains a solution @post testing post tag @return true if rows check out, false o/w */ protected boolean checkRows(){ for (int row = 0; row < SIZE; row++){ for (int i = 0; i < SIZE; i++){ int count = 0; for (int col = 0; col < SIZE; col++){ if (board[row][col] == i){ count++; } } if (count != 1){ return false; } } } return true; } /** Check columns verifies that each column contains 1-9 uniquely @pre rows checked out @post now rows and cols check out, just subsquares left to check @return true if all columns contain 1-9 uniquely */ protected boolean checkCols(){ for (int col = 0; col < SIZE; col++){ for (int i = 0; i < SIZE; i++){ int count = 0; for (int row = 0; row < SIZE; row++){ if (board[row][col] == i){ count++; } } if (count != 1){ return false; } } } return true; } protected boolean checkBlocks(){ // an exercise left for the reader // What's a good way to verify the blocks? return true; } public static void main(String[] args){ Scanner s = new Scanner(System.in); SudokuVerifier game = new SudokuVerifier(); int row = 0; int col = 0; // read in the board from a file while (s.hasNextLine()){ String line = s.nextLine(); Scanner t = new Scanner(line); while (t.hasNextInt()){ int num = t.nextInt(); game.board[row][col] = num - 1; col++; } col = 0; row++; } if (game.checkRows() && game.checkCols() && game.checkBlocks()){ System.out.println("It's a solution!"); }else{ System.out.println("Not a solution. Sorry."); } } }