Skip to content

Instantly share code, notes, and snippets.

@rabestro
Last active July 26, 2020 15:54
Show Gist options
  • Save rabestro/85823ef5ec7144082b68e53ca55373df to your computer and use it in GitHub Desktop.
Save rabestro/85823ef5ec7144082b68e53ca55373df to your computer and use it in GitHub Desktop.
Check sudoku of any dimension
import java.util.Scanner;
import java.util.stream.IntStream;
import static java.util.stream.IntStream.range;
public class Main {
public static void main(String[] args) {
final var scanner = new Scanner(System.in);
final var n = scanner.nextInt();
final var m = n * n;
final var sudoku = new Sudoku(n, scanner.tokens().limit(m * m).mapToInt(Integer::parseInt).toArray());
System.out.println(sudoku.check() ? "YES" : "NO");
}
}
class Sudoku {
private final int squareSize;
private final int maxNumber;
private final int[] board;
Sudoku(final int squareSize, final int[] board) {
this.squareSize = squareSize;
this.maxNumber = squareSize * squareSize;
this.board = board;
}
boolean check() {
return range(0, maxNumber).allMatch(this::checkRowColSquare);
}
boolean checkRowColSquare(final int i) {
return checkRow(i) && checkCol(i) && checkSquare(i);
}
boolean checkRow(final int row) {
return checkNumbers(range(0, maxNumber).map(i -> board[row * maxNumber + i]));
}
boolean checkCol(final int col) {
return checkNumbers(range(0, maxNumber).map(i -> board[maxNumber * i + col]));
}
boolean checkSquare(final int square) {
final int row = square / squareSize * squareSize;
final int col = square % squareSize * squareSize;
return checkNumbers(range(0, maxNumber)
.map(i -> board[(row + i / squareSize) * maxNumber + col + i % squareSize]));
}
boolean checkNumbers(IntStream numbers) {
return numbers.filter(i -> i > 0 && i <= maxNumber).distinct().count() == maxNumber;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment