Skip to content

Instantly share code, notes, and snippets.

@danielomiya
Created April 26, 2021 04:33
Show Gist options
  • Select an option

  • Save danielomiya/f35cc553e518323b4913f49f61026dde to your computer and use it in GitHub Desktop.

Select an option

Save danielomiya/f35cc553e518323b4913f49f61026dde to your computer and use it in GitHub Desktop.
Simple (and probably naive) validation of a Sudoku instance in Java.
import java.util.Arrays;
import java.util.stream.IntStream;
public final class Sudoku {
private static final int[][] SQUARE_CORNERS = new int[9][2];
static {
var lastIndex = 0;
for (var i = 0; i < 9; i += 3) {
for (var j = 0; j < 9; j += 3) {
SQUARE_CORNERS[lastIndex][0] = i;
SQUARE_CORNERS[lastIndex++][1] = j;
}
}
}
private final int[][] matrix;
public Sudoku() {
this(new int[9][9]);
}
public Sudoku(final int[][] matrix) {
this.matrix = matrix;
}
public static void main(String[] args) {
final var s = new Sudoku(new int[][]{
{8, 2, 7, 1, 5, 4, 3, 9, 6},
{9, 6, 5, 3, 2, 7, 1, 4, 8},
{3, 4, 1, 6, 8, 9, 7, 5, 2},
{5, 9, 3, 4, 6, 8, 2, 7, 1},
{4, 7, 2, 5, 1, 3, 6, 8, 9},
{6, 1, 8, 9, 7, 2, 4, 3, 5},
{7, 8, 6, 2, 3, 5, 9, 1, 4},
{1, 5, 4, 7, 9, 6, 8, 2, 3},
{2, 3, 9, 8, 4, 1, 5, 6, 7},
});
System.out.println(s);
System.out.println(s.isValid());
}
private static boolean isNumberValid(final int number) {
return number >= 1 && number <= 9;
}
private static boolean isSectionValid(final IntStream stream) {
final var differentElements = stream
.filter(Sudoku::isNumberValid)
.distinct()
.count();
return differentElements == 9;
}
public int[][] getMatrix() {
return matrix;
}
private void validateIndex(final int index) {
if (index >= 0 && index < 9) return;
throw new IllegalArgumentException("invalid index");
}
public boolean isRowValid(final int index) {
validateIndex(index);
final var row = matrix[index];
return isSectionValid(Arrays.stream(row));
}
public boolean isColValid(final int index) {
validateIndex(index);
final var col = Arrays.stream(matrix).mapToInt(x -> x[index]);
return isSectionValid(col);
}
public boolean isSquareValid(final int row, final int col) {
final var cols = Arrays.stream(matrix).skip(row).limit(3); // limit rows
final var square = cols.flatMap(r -> Arrays.stream(r).skip(col).limit(3).boxed()); // limit cols
return isSectionValid(square.mapToInt(Integer::intValue));
}
public boolean isValid() {
for (var i = 0; i < 9; i++)
if (!(isRowValid(i) && isColValid(i))) return false;
for (final var square : SQUARE_CORNERS)
if (!isSquareValid(square[0], square[1])) return false;
return true;
}
@Override
public String toString() {
return "Sudoku{" +
"matrix=" +
Arrays.toString(Arrays.stream(matrix).map(x -> '\n' + Arrays.toString(x)).toArray()) +
'}';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment