Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <array>
- #include <algorithm>
- #include <random>
- #include <bitset>
- typedef unsigned int uint;
- class Sudoku
- {
- public:
- Sudoku() noexcept
- : gen(rd())
- {
- square.fill(0);
- std::generate( std::begin(square),
- std::end(square),
- [](){ static uint i = 0; return ++i; });
- generate();
- }
- void print() noexcept
- {
- for (int i = 0; i < 81; ++i)
- {
- if (!(i%9) && i)
- std::cout << "|\n";
- if (!(i%27))
- std::cout << "+---+---+---+\n";
- if (!(i%3))
- std::cout << "|";
- std::cout << board[i];
- }
- std::cout << "|\n+---+---+---+\n";
- std::cout << std::flush;
- }
- void generate() noexcept
- {
- // Use rejection sampling
- do
- {
- fillBoardSquare(0); fillBoardSquare(3); fillBoardSquare(6);
- fillBoardSquare(27); fillBoardSquare(30); fillBoardSquare(33);
- fillBoardSquare(54); fillBoardSquare(57); fillBoardSquare(60);
- } while (!validate());
- }
- private:
- std::array<uint,81> board;
- std::array<uint,9> square;
- std::random_device rd;
- std::mt19937 gen;
- void fillBoardSquare(size_t anchor) noexcept
- {
- std::shuffle(std::begin(square),std::end(square),gen);
- for (size_t i = 0; i < 9; ++i)
- {
- board[anchor+(i%3)] = square[i];
- if (i%3 == 2)
- anchor += 9;
- }
- }
- bool validate() noexcept
- {
- bool valid = true;
- std::bitset<9> length;
- uint counter = 0;
- for (size_t i = 0; i < 9 && valid; ++i)
- {
- for (size_t j = 0; j < 9 && valid; ++j)
- length.set(board[i + j*9]-1);
- if (valid = length.all())
- length.reset();
- ++counter;
- }
- for (size_t j = 0; j < 9 && valid; ++j)
- {
- for (size_t i = 0; i < 9 && valid; ++i)
- length.set(board[i + j*9]-1);
- if (valid = length.all())
- length.reset();
- ++counter;
- }
- return valid;
- }
- };
- int main()
- {
- std::cout << "Here is your sudoku:\n";
- // You may be waiting a while
- Sudoku sudoku;
- sudoku.print();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement