Files
nd-wfc/demos/sudoku/sudoku_wfc.cpp
cdemeyer-teachx 76ad49b05a wfc compiled
2025-08-24 17:15:09 +09:00

58 lines
2.0 KiB
C++

#include <nd-wfc/wfc.hpp>
#include <nd-wfc/worlds.hpp>
#include <iostream>
int main()
{
std::cout << "Running Sudoku WFC" << std::endl;
auto sudokuSolver = WFC::Builder<WFC::Array2D<uint8_t, 9, 9>, uint8_t>()
.DefineIDs<1, 2, 3, 4, 5, 6, 7, 8, 9>()
.Variable<1, 2, 3, 4, 5, 6, 7, 8, 9>([](WFC::Array2D<uint8_t, 9, 9>&, size_t index, WFC::WorldValue<uint8_t> val, auto& constrainer) {
size_t x = index % 9;
size_t y = index / 9;
// Add row constraints (same row, different columns)
for (size_t i = 0; i < 9; ++i) {
if (i != x) constrainer.Exclude(val, i + y * 9);
}
// Add column constraints (same column, different rows)
for (size_t i = 0; i < 9; ++i) {
if (i != y) constrainer.Exclude(val,x + i * 9);
}
// Add box constraints (3x3 box)
int box_x = (x / 3) * 3;
int box_y = (y / 3) * 3;
for (size_t j = 0; j < 3; ++j) {
for (size_t k = 0; k < 3; ++k) {
int cell_x = box_x + j;
int cell_y = box_y + k;
size_t cell_index = cell_x + cell_y * 9;
if (cell_index != index) {
constrainer.Exclude(val, cell_index);
}
}
}
})
.build();
WFC::Array2D<uint8_t, 9, 9> sudokuWorld;
bool success = sudokuSolver.Run(sudokuWorld);
if (success) {
std::cout << "Sudoku solved successfully!" << std::endl;
// Print the solved sudoku
for (size_t y = 0; y < 9; ++y) {
for (size_t x = 0; x < 9; ++x) {
std::cout << static_cast<int>(sudokuWorld.at(x, y)) << " ";
if (x == 2 || x == 5) std::cout << "| ";
}
std::cout << std::endl;
if (y == 2 || y == 5) std::cout << "------+-------+------" << std::endl;
}
} else {
std::cout << "Failed to solve sudoku!" << std::endl;
}
}