Created
February 19, 2019 10:10
-
-
Save hsandid/db6debd17350c5dd178e2d5ceff29937 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Separe main code into more functions | |
//Add a stack which stores the previouses sudokus | |
//and comes back to the latest correct version if any error is detected | |
#include <iostream> | |
#include <time.h> | |
#include <stdlib.h> | |
using namespace std; | |
bool checkPlacement(int i,int x,int y,int grid[9][9]) | |
{ | |
bool isPlaceable = true; | |
if (grid[x][y] == i) | |
{ | |
isPlaceable = false; | |
} | |
for (int k = 0; k < 9; k++) | |
{ | |
if (grid[k][y] == i ) | |
{ | |
isPlaceable = false; | |
break; | |
} | |
} | |
for (int l = 0; l < 9; l++) | |
{ | |
if (grid[x][l] == i ) | |
{ | |
isPlaceable = false; | |
break; | |
} | |
} | |
int tempX; | |
int tempY; | |
if (x == 0 || x == 1 || x == 2) | |
{ | |
tempX = 0; | |
} | |
else if (x == 3 || x == 4 || x == 5) | |
{ | |
tempX = 3; | |
} | |
else if (x == 6 || x == 7 || x == 8) | |
{ | |
tempX = 6; | |
} | |
if (y == 0 || y == 1 || y == 2) | |
{ | |
tempY = 0; | |
} | |
else if (y == 3 || y == 4 || y == 5) | |
{ | |
tempY = 3; | |
} | |
else if (y == 6 || y == 7 || y == 8) | |
{ | |
tempY = 6; | |
} | |
for (int n = 0; n < 3; n++) | |
{ | |
for (int h = 0; h < 3; h++) | |
{ | |
if (grid[tempX + n][tempY + h] == i) | |
{ | |
isPlaceable = false; | |
} | |
} | |
} | |
return isPlaceable; | |
} | |
void printGrid(int grid[9][9]) | |
{ | |
int counterX = 0; | |
for (int i = 0; i < 9; i++) | |
{ | |
if (counterX % 3 == 0) | |
{ | |
cout << endl << endl; | |
} | |
else | |
{ | |
cout << endl; | |
} | |
counterX++; | |
int counterY = 0; | |
for (int j = 0; j < 9; j++) | |
{ | |
if (counterY % 3 == 0) | |
{ | |
cout <<" "; | |
} | |
cout << grid[i][j]; | |
counterY++; | |
} | |
} | |
cout << endl << endl; | |
} | |
void initGrid(int grid[9][9]) | |
{ | |
for (int i = 0; i < 9; i++) | |
{ | |
for (int j = 0; j < 9; j++) | |
{ | |
grid[i][j]=0; | |
} | |
} | |
} | |
void main() | |
{ | |
srand(time(NULL)); | |
int grid[9][9]; | |
initGrid(grid); | |
for (int i = 1; i < 3; i++) | |
{ | |
int counter = 0; | |
while (counter < 9) | |
{ | |
int x = rand() % 9; | |
int y = rand() % 9; | |
bool test=checkPlacement(i, x, y,grid); | |
if (test == true) | |
{ | |
counter++; | |
grid[x][y] = i; | |
} | |
} | |
} | |
printGrid(grid); | |
system("pause"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment