Last active
July 26, 2020 15:54
-
-
Save rabestro/85823ef5ec7144082b68e53ca55373df to your computer and use it in GitHub Desktop.
Check sudoku of any dimension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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