sudoku: constraints: add sudoku rules constraints

This commit is contained in:
Bruno BELANYI 2020-12-21 20:40:05 +01:00
parent ddb7dad60c
commit 36be2b2eb2
3 changed files with 64 additions and 0 deletions

View file

@ -9,6 +9,7 @@ project(
)
sources = [
'src/constraints.c',
'src/main.c',
'src/sudoku.c',
]

50
src/constraints.c Normal file
View file

@ -0,0 +1,50 @@
#include "constraints.h"
#include "sudoku.h"
bool line_violation(const struct sudoku *grid, size_t i, size_t j) {
if (!grid)
return true;
for (size_t l = 0; l < 9; ++l) {
if (l == i)
continue;
if (grid->grid[l][j] == grid->grid[i][j])
return true;
}
return false;
}
bool column_violation(const struct sudoku *grid, size_t i, size_t j) {
if (!grid)
return true;
for (size_t c = 0; c < 9; ++c) {
if (c == j)
continue;
if (grid->grid[i][c] == grid->grid[i][j])
return true;
}
return false;
}
bool square_violation(const struct sudoku *grid, size_t i, size_t j) {
if (!grid)
return true;
const size_t x = i / 3;
const size_t y = j / 3;
for (size_t l = 3 * x; l < 3 * (x + 1); ++l) {
for (size_t c = 3 * y; c < 3 * (y + 1); ++c) {
if (l == i && c == j)
continue;
if (grid->grid[l][c] == grid->grid[i][j])
return true;
}
}
return false;
}

13
src/constraints.h Normal file
View file

@ -0,0 +1,13 @@
#ifndef CONSTRAINTS_H
#define CONSTRAINTS_H
#include <stdbool.h>
#include <stddef.h>
struct sudoku;
bool line_violation(const struct sudoku *grid, size_t i, size_t j);
bool column_violation(const struct sudoku *grid, size_t i, size_t j);
bool square_violation(const struct sudoku *grid, size_t i, size_t j);
#endif /* !CONSTRAINTS_H */