// SudokuHelperB.java, Ole Marius Hoel Rindal import easyIO.*; class SudokuHelperB { public static void main(String[] args) { Methods go = new Methods(); go.makeBoard(); go.printBoard(); go.loop(); } } class Methods { int[][] board = new int[9][9]; int[] nums = new int[9]; int run = 0; In infile = new In("sudoku1.txt"); In in = new In(); //Reads the file into a two dimensional array void makeBoard() { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { board[i][j] = Integer.parseInt(infile.inWord()); } } } //Print out the board void printBoard() { for (int i = 0; i < board.length; i++) { System.out.print("---" + (i + 1) + "[ "); for (int j = 0; j < board[0].length; j++) { System.out.print(board[i][j]+" "); } System.out.println("]---"); } System.out.println(); } void loop() {//The loop running the program String input = ""; boolean finish = false; while (!finish) { run++; for (int i = 1; i < 10; i++) {//Feeds the algorithm will all the places on the board for (int j = 1; j < 10; j++) { for (int k = 0; k < nums.length; k++) {//Gives the nums array "fresh" numbers nums[k] = (k + 1); } checkLines(i, j);//Starts the method with the generated place } } if (run == 2) {//Check if it has been two runs without new numbers finish = true; printBoard(); } } } void checkLines(int row, int col) { if (board[row-1][col-1] == 0) {//See if the place doesn't have a number //Check the line vertically for (int i = 0; i < board.length; i++) { for (int j = 0; j < nums.length; j++) { if (board[i][col-1] == nums[j]) { nums[j] = -1; } } } //Check the line horizontally for (int i = 0; i < board.length; i++) { for (int j = 0; j < nums.length; j++) { if (board[row-1][i] == nums[j]) { nums[j] = -1; } } } checkQuadrant(row,col);//When done checking the lines do the CheckQuadrant() method } } void checkQuadrant(int row, int col) { //Divide the board into quadrants, and check the numbers in the numbers quadrant //Find the location of the quadrant (its top left corner) int quadrantRow = 0; int quadrantCol = 0; if (row > 3 && row <= 6) quadrantRow = 3; if (row > 6 && row <= 9) quadrantRow = 6; if (col > 3 && col <= 6) quadrantCol = 3; if (col > 6 && col <= 9) quadrantCol = 6; for (int i = quadrantRow; i < quadrantRow + 3; i++) { for (int l = quadrantCol; l < quadrantCol + 3; l++) { for (int j = 0; j < nums.length; j++) { if (board[i][l] == nums[j]) { nums[j] = -1; } } } } int count = 0; int rightNumber = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] != -1) { rightNumber = nums[i]; count++; } } if (count == 1) {//if there is only one right number, it's "written" on the board board[row-1][col-1] = rightNumber; run = 0;//if a new number is found, set the run count to 0 } } }