commit 57ef6777cbec5c9f61b1fbe942e5732fb7aa68e7
Author: Dimitrije Dobrota <mail@dimitrijedobrota.com>
Date: Tue, 2 Apr 2024 19:48:03 +0200
Proof of concept bitboard sudoku
Diffstat:
A | main.cpp | | | 107 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 107 insertions(+), 0 deletions(-)
diff --git a/main.cpp b/main.cpp
@@ -0,0 +1,107 @@
+#include <bit>
+#include <bitset>
+#include <cinttypes>
+#include <iomanip>
+#include <iostream>
+
+static const std::int64_t mask_field = (1 << 9) - 1;
+
+class Row {
+public:
+ Row(std::uint64_t value = 0) : val(value) {}
+ operator std::uint64_t() const { return val; }
+
+ std::uint64_t get(uint8_t field) const {
+ uint64_t shift = field * 9;
+ return (val >> shift) & mask_field;
+ }
+
+ void set(uint8_t field, uint8_t value) {
+ uint64_t shift = field * 9;
+ val &= ~(mask_field << shift);
+ val |= (1ull << value) << shift;
+ }
+
+ friend std::ostream &operator<<(std::ostream &os, const Row r) {
+ return os << std::setfill('0') << std::setw(14) << std::hex
+ << (r.val & ((1ul << 54) - 1));
+ }
+
+private:
+ std::uint64_t val;
+};
+
+class Subgrid {
+public:
+ Subgrid() {}
+
+ std::uint64_t get(uint8_t field) const {
+ return rows[field / 3].get(field % 3);
+ }
+
+ void set(uint8_t field, uint8_t value) {
+ rows[field / 3].set(field % 3, value);
+ rows[2 - field % 3].set(3 + field / 3, value);
+ }
+
+ friend std::ostream &operator<<(std::ostream &os, const Subgrid &b) {
+
+ for (int i = 0; i < 3; i++) {
+ os << b.rows[i] << " ";
+ }
+ return os;
+ }
+
+private:
+ Row rows[3] = {11111111, 22222222, 33333333};
+};
+
+class Grid {
+public:
+ void set(uint8_t subgrid, uint8_t field, uint8_t value) {
+ subgrids[subgrid].set(field, value);
+ }
+
+ void print() const {
+ for (int i = 0; i < 9; i++) {
+ for (int j = 0; j < 9; j++) {
+ std::bitset<9> value =
+ subgrids[(i / 3) * 3 + j / 3].get((i % 3) * 3 + j % 3);
+ std::cout << value << " ";
+ if (j % 3 == 2)
+ std::cout << " ";
+ }
+ std::cout << std::endl;
+ if (i % 3 == 2)
+ std::cout << std::endl;
+ }
+ }
+
+ friend std::ostream &operator<<(std::ostream &os, const Grid &g) {
+ for (int i = 0; i < 9; i++) {
+ std::cout << g.subgrids[i] << std::endl;
+ }
+ return os;
+ }
+
+private:
+ Subgrid subgrids[9];
+};
+
+int main(void) {
+ Grid g;
+
+ g.set(0, 0, 0);
+ g.set(0, 1, 1);
+ g.set(0, 2, 2);
+ g.set(0, 3, 3);
+ g.set(0, 4, 4);
+ g.set(0, 5, 5);
+ g.set(0, 6, 6);
+ g.set(0, 7, 7);
+ g.set(0, 8, 8);
+ std::cout << g << std::endl;
+ g.print();
+
+ return 0;
+}