1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/src/de/uapcore/sudoku/Solver.java Sat Jan 26 17:42:07 2013 +0100 1.3 @@ -0,0 +1,122 @@ 1.4 +package de.uapcore.sudoku; 1.5 + 1.6 +/** 1.7 + * 1.8 + * @author mike 1.9 + */ 1.10 +public final class Solver { 1.11 + 1.12 + public Solver() { 1.13 + } 1.14 + 1.15 + public boolean check(Field f) { 1.16 + int line[]; 1.17 + for (int i = 0 ; i < 9 ; i++) { 1.18 + line = getRow(f, i); 1.19 + if (!valid(line)) { 1.20 + return false; 1.21 + } 1.22 + line = getColumn(f, i); 1.23 + if (!valid(line)) { 1.24 + return false; 1.25 + } 1.26 + } 1.27 + 1.28 + int square[][]; 1.29 + for (int x = 0 ; x < 3 ; x++) { 1.30 + for (int y = 0 ; y < 3 ; y++) { 1.31 + square = getSquare(f, x, y); 1.32 + if (!valid(square)) { 1.33 + return false; 1.34 + } 1.35 + } 1.36 + } 1.37 + 1.38 + return true; 1.39 + } 1.40 + 1.41 + private boolean complete(int[][] square) { 1.42 + for (int x = 0 ; x < 3 ; x++) { 1.43 + for (int y = 0 ; y < 3 ; y++) { 1.44 + if (square[x][y] == 0) { 1.45 + return false; 1.46 + } 1.47 + } 1.48 + } 1.49 + return true; 1.50 + } 1.51 + 1.52 + private boolean complete(int[] line) { 1.53 + for (int i = 0 ; i < 9 ; i++) { 1.54 + if (line[i] == 0) { 1.55 + return false; 1.56 + } 1.57 + } 1.58 + return true; 1.59 + } 1.60 + 1.61 + private boolean valid(int[] line) { 1.62 + int numbers[] = new int[9]; 1.63 + for (int i = 0 ; i < 9 ; i++) { 1.64 + int l = line[i]-1; 1.65 + if (l >= 0) { 1.66 + if (++numbers[l] > 1) { 1.67 + return false; 1.68 + } 1.69 + } 1.70 + } 1.71 + 1.72 + return true; 1.73 + } 1.74 + 1.75 + private boolean valid(int[][] square) { 1.76 + int[] line = new int[9]; 1.77 + for (int x = 0 ; x < 3 ; x++) { 1.78 + for (int y = 0 ; y < 3 ; y++) { 1.79 + line[3*x+y] = square[x][y]; 1.80 + } 1.81 + } 1.82 + return valid(line); 1.83 + } 1.84 + 1.85 + private int[][] getSquare(Field f, int x, int y) { 1.86 + if (x < 0 || x > 2 || y < 0 || y > 2) { 1.87 + throw new IllegalArgumentException("Invalid square coordinates"); 1.88 + } 1.89 + int[][] square = new int[3][3]; 1.90 + 1.91 + for (int u = 0 ; u < 3 ; u++) { 1.92 + for (int v = 0 ; v < 3 ; v++) { 1.93 + square[u][v] = f.getCellValue(3*x+u, 3*y+v); 1.94 + } 1.95 + } 1.96 + 1.97 + return square; 1.98 + } 1.99 + 1.100 + private int[] getRow(Field f, int y) { 1.101 + if (y < 0 || y > 8) { 1.102 + throw new IllegalArgumentException("Invalid row number"); 1.103 + } 1.104 + int row[] = new int[9]; 1.105 + 1.106 + for (int x = 0 ; x < 9 ; x++) { 1.107 + row[x] = f.getCellValue(x, y); 1.108 + } 1.109 + 1.110 + return row; 1.111 + } 1.112 + 1.113 + private int[] getColumn(Field f, int x) { 1.114 + if (x < 0 || x > 8) { 1.115 + throw new IllegalArgumentException("Invalid column number"); 1.116 + } 1.117 + int column[] = new int[9]; 1.118 + 1.119 + for (int y = 0 ; y < 9 ; y++) { 1.120 + column[y] = f.getCellValue(x, y); 1.121 + } 1.122 + 1.123 + return column; 1.124 + } 1.125 +}