diff --git a/arrays/src/arrays/Main.java b/arrays/src/arrays/Main.java index 84c6c76..0925372 100644 --- a/arrays/src/arrays/Main.java +++ b/arrays/src/arrays/Main.java @@ -37,7 +37,67 @@ class Sieve implements Iterator { } } +class Sudoku { + static boolean solved(int[][] puz) { + // First check the data is shaped correctly. + if (puz.length != 9) return false; + for (int[] row : puz) + if (row.length != 9) return false; + + // Make sure they're all valid integers. + for (int[] row : puz) + for (int n : row) + if (n < 1 || n > 9) return false; + + // Check that there'ren't any repeats in a row. + for (int[] row : puz) { int[] } + } +} + class Examples { + void testSudoku(Tester t) { + int[][] testPuz1 = { + {5, 3, 4, 6, 7, 8, 9, 1, 2}, {6, 7, 2, 1, 9, 5, 3, 4, 8}, + {1, 9, 8, 3, 4, 2, 5, 6, 7}, {8, 5, 9, 7, 6, 1, 4, 2, 3}, + {4, 2, 6, 8, 5, 3, 7, 9, 1}, {7, 1, 3, 9, 2, 4, 8, 5, 6}, + {9, 6, 1, 5, 3, 7, 2, 8, 4}, {2, 8, 7, 4, 1, 9, 6, 3, 5}, + {3, 4, 5, 2, 8, 6, 1, 7, 9} + }; + int[][] testPuz2 = { + {5, 3, 4, 6, 7, 8, 9, 1, 2}, {6, 7, 2, 1, 9, 5, 3, 4, 8}, + {1, 9, 8, 3, 4, 2, 5, 6, 7}, {8, 5, 9, 7, 6, 1, 4, 2, 3}, + {4, 2, 6, 8, 5, 3, 7, 9, 1}, {7, 1, 3, 9, 2, 4, 8, 5, 6}, + {9, 6, 4, 5, 3, 7, 2, 8, 4}, // There're 2 4s here. + {2, 8, 7, 4, 1, 9, 6, 3, 5}, {3, 4, 5, 2, 8, 6, 1, 7, 9} + }; + int[][] testPuz3 = { + // Incomplete, missing a row. + {5, 3, 4, 6, 7, 8, 9, 1, 2}, {6, 7, 2, 1, 9, 5, 3, 4, 8}, + {1, 9, 8, 3, 4, 2, 5, 6, 7}, {8, 5, 9, 7, 6, 1, 4, 2, 3}, + {4, 2, 6, 8, 5, 3, 7, 9, 1}, {7, 1, 3, 9, 2, 4, 8, 5, 6}, + {2, 8, 7, 4, 1, 9, 6, 3, 5}, {3, 4, 5, 2, 8, 6, 1, 7, 9} + }; + int[][] testPuz4 = { + {5, 3, 4, 6, 7, 8, 9, 1, 2}, {6, 7, 2, 1, 9, 5, 3, 4, 8}, + {1, 9, 8, 3, 4, 2, 5, 6, 7}, {8, 5, 9, 7, 6, 1, 4, 2, 3}, + {4, 2, 6, 8, 5, 3, 7, 9, 1}, {7, 1, 3, 9, 2, 4, 8, 5, 6}, + {9, 6, 1, 5, 3, 7, 2, 8, 4}, {2, 8, 7, 4, 1, 9, 6, 3, 5}, + {3, 4, 5, 8, 6, 1, 7, 9} // Incomplete, missing a number. + }; + int[][] testPuz5 = { + {5, 3, 4, 6, 7, 8, 9, 1, 2}, {6, 7, 2, 1, 9, 5, 3, 4, 8}, + {1, 9, 8, 3, 4, 2, 5, 6, 7}, {8, 5, 9, 7, 6, 1, 4, 2, 3}, + {4, 2, 6, 0, 5, 3, 7, 9, 1}, // Invalid number. + {7, 1, 3, 9, 2, 4, 8, 5, 6}, {9, 6, 1, 5, 3, 7, 2, 8, 4}, + {2, 8, 7, 4, 1, 9, 6, 3, 5}, {3, 4, 5, 2, 8, 6, 1, 7, 9} + }; + + t.checkExpect(Sudoku.solved(testPuz1), true); + t.checkExpect(Sudoku.solved(testPuz2), false); + t.checkExpect(Sudoku.solved(testPuz3), false); + t.checkExpect(Sudoku.solved(testPuz4), false); + t.checkExpect(Sudoku.solved(testPuz5), false); + } void testSieve(Tester t) { Sieve sieve = new Sieve(29); t.checkExpect(sieve.hasNext(), true);