Skip to content

Instantly share code, notes, and snippets.

@Acarus
Last active August 26, 2015 21:53
Show Gist options
  • Save Acarus/fd9ebf669c9a3c944a87 to your computer and use it in GitHub Desktop.
Save Acarus/fd9ebf669c9a3c944a87 to your computer and use it in GitHub Desktop.
Sudoku input data generator
#include <iostream>
#include <ctime>
#include <stdlib.h>
#include <vector>
using namespace std;
class Solution {
public:
bool findFreePos(vector< vector<char> >& board, int& x, int& y) {
for(x = 0; x < 9; x++)
for(y = 0; y < 9; y++)
if(board[x][y] == '.')
return true;
return false;
}
bool canSet(vector< vector<char> >& board, int x, int y, char c) {
for(int i = 0; i < 9; i++)
if(board[x][i] == c)
return false;
for(int i = 0; i < 9; i++)
if(board[i][y] == c)
return false;
for(int i = (x/3)*3; i < (x/3)*3 + 3; i++)
for(int j = (y/3)*3; j < (y/3)*3 + 3; j++)
if(board[i][j] == c)
return false;
return true;
}
bool solve(vector< vector<char> >& board) {
int x, y;
if(!findFreePos(board, x, y))
return true;
for(char i = '1'; i <= '9'; i++)
if(canSet(board, x, y, i)) {
board[x][y] = i;
if(solve(board))
return true;
board[x][y] = '.';
}
return false;
}
void solveSudoku(vector< vector<char> >& board) {
solve(board);
}
};
const int MAX_COUNT = 65;
const int MIN_COUNT = 40;
int main(void) {
srand(time(0));
Solution s;
vector<vector<char>> m(9, vector<char>(9, '.'));
// fill first row with random
vector<int> v;
for(int i = 1; i <= 9; i++)
v.push_back(i);
for(int i = 0; i < 9; i++) {
int index = rand() % v.size();
m[0][i] = v[index] + '0';
v.erase(v.begin() + index);
}
// solve sudoku
s.solveSudoku(m);
// erase some cells
vector< pair<int, int> > filledCells;
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
filledCells.push_back(make_pair(i, j));
int countToDelete = random() % (MAX_COUNT - MIN_COUNT) + MIN_COUNT;
for(int i = 0; i < countToDelete; i++) {
int index = rand() % filledCells.size();
int x = filledCells[index].first;
int y =filledCells[index].second;
filledCells.erase(filledCells.begin() + index);
m[x][y] = '.';
}
// print result
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++)
cout << m[i][j] << " ";
cout << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment