1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-08 18:49:07 +01:00
CodeWars/4kyu/sudoku_solution_validator/solution.cs
Matej Focko fc899b0b02
chore: initial commit
Signed-off-by: Matej Focko <mfocko@redhat.com>
2021-12-28 16:19:58 +01:00

53 lines
1.2 KiB
C#

using System.Collections.Generic;
public class Sudoku {
private static readonly int FULL = (~(((~0) >> 9) << 9)) << 1;
private static IEnumerable<(int, int)> Row(int row) {
for (var col = 0; col < 9; col++) {
yield return (row, col);
}
}
private static IEnumerable<(int, int)> Column(int column) {
for (var row = 0; row < 9; row++) {
yield return (row, column);
}
}
private static IEnumerable<(int, int)> Box(int k) {
var row = 3 * (k / 3);
var col = 3 * (k % 3);
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
yield return (row + i, col + j);
}
}
}
private static bool Valid(int[][] board, IEnumerable<(int, int)> coordinates) {
var encountered = 0;
foreach (var (row, col) in coordinates) {
if (board[row][col] == 0) {
return false;
} else if ((encountered & (1 << board[row][col])) != 0) {
return false;
}
encountered |= 1 << board[row][col];
}
return encountered == FULL;
}
public static bool ValidateSolution(int[][] board) {
for (var i = 0; i < 9; i++) {
if (!Valid(board, Row(i)) || !Valid(board, Column(i)) || !Valid(board, Box(i))) {
return false;
}
}
return true;
}
}