Suitably geeky - Sudoku solver
In category Geebin on 28 Apr 2006 @ 01:47 am
So I've been working on a lot of new photos and a few other projects just haven't been keeping any nerdy readers suitably entertained? Well this is something I wrote a while ago to solve those really irritating Sudoku problems with glorified trial-and-error solutions. This is only a snippet of code so download the full code file to compile and run. It's a simple program written in C because I was originally worried about it taking too long to solve and I wanted to make it as efficient as possible. In the end, this solved the "diabolical" difficulty puzzles in about 2 seconds. Maybe it's time to add a GUI?
I've already had long discussions with people who want to defend Sudoku puzzles as a real mental challenge but feel free to comment here as well.
I've already had long discussions with people who want to defend Sudoku puzzles as a real mental challenge but feel free to comment here as well.
/*
Name: solve
Parameters: x and y coordinates for the game board.
Description: Solve a value in the puzzle. If it can't be solved, The previous
vaules are wrong.
Method: Check each row, column and 3x3 square for numbers. Anything not found
is a possible value. Pick the last one, put it in the attempts[] array
and board value and move on.
If there are no possible values left. Set this value to 0, reset all
attempts and try re-solve the previous.
Returns: None
*/
int solve(int x, int y)
{
/* Assume all numbers are possible for a square */
int poss[]={1,2,3,4,5,6,7,8,9};
/* Meaning there are 9 possible values */
int possCount = 9;
int i, j, m, n = 0;
/* Get rid of values we've tried before that didn't work. */
for(i=0;i<9;i++)
{
if((board[x][y].attempts[i]==poss[i]) && (board[x][y].attempts[i] != 0))
{
poss[i]=0;
possCount--;
}
}
/* Get rid of any values that are elsewhere in the row */
for(i=0;i<9;i++)
{
if(board[x][i].value == poss[board[x][i].value-1] && board[x][i].value!=0)
{
poss[board[x][i].value-1]=0;
possCount--;
}
}
/* Get rid of any values that are elsewhere in the column */
for(i=0;i<9;i++)
{
if(board[i][y].value == poss[board[i][y].value-1]&& board[i][y].value!=0)
{
poss[board[i][y].value-1]=0;
possCount--;
}
}
/* Get rid of any values that are elsewhere in the 3x3 square */
m = x-x%3;
n = y-y%3;
for(i=m;i<m+3;i++)
{
for(j=n;j<n+3;j++)
{
if(board[i][j].value == poss[board[i][j].value-1] && board[i][j].value!=0)
{
poss[board[i][j].value-1]=0;
possCount--;
}
}
}
/* Are there any numbers left to put into this square? */
if(possCount < 1)
{
/* No. so reset valeus and BACKTRACK */
resetArray(board[x][y].attempts);
board[x][y].value = 0;
move(-1);
}
else
{
/* Yes. so set values and CONTINUE */
for(i=0;i<9;i++)
{
if(poss[i]!=0)
{
board[x][y].value = poss[i];
}
}
/* The value must be stored in its correct position. attempts[value-1] */
board[x][y].attempts[board[x][y].value-1] = board[x][y].value;
move(1);
}
}



