mirror of
https://gitlab.com/mfocko/CodeWars.git
synced 2024-11-22 08:33:48 +01:00
53 lines
1.2 KiB
C#
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;
|
|
}
|
|
}
|