1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
|
/**********************************************************************
* Function will write the file to the file the user chooses
***********************************************************************/
void writeFile(char sudokuBoard[][9])
{
//Declare file output
char fileDestination[256];
ofstream fout;
//Asking for user input
cout << "What file would you like to write your board to: ";
cin >> fileDestination;
//Open destination file & error checking
fout.open(fileDestination);
//Writes board to file
for (int row = 0; row < 9; row++)
{
for (int col = 0; col < 9; col++)
{
fout << sudokuBoard[col][row];
}
}
if (fout.fail())
{
cout << "Written unsuccessfully";
}
else
cout << "Board written successfully\n";
//Close file
fout.close();
exit(0);
}
// 2017-07-11: added functions
/* checkCellRangesAndEmptiness: returns false if any index is out of range or
* if the cell is not empty.
* Otherwise returns true.
*/
bool checkCellRangesAndEmptiness(char sudokuBoard[][9], int col, int row)
{
if(col < 0 || 8 < col || row < 0 || 8 < row) { return false; }
if(sudokuBoard[col][row] != '0') { return false; }
return true;
}
/* checkColMatches: returns true if any matches found in the same column.
* Otherwise returns false.
*/
bool checkColMatches(char sudokuBoard[][9], int col, char value)
{
for(int i{}; i<8; i++) {
if(sudokuBoard[col][i] == value) { return true;}
}
return false;
}
/* checkRowMatches: returns true if any matches found in the same row.
* Otherwise returns false.
*/
bool checkRowMatches(char sudokuBoard[][9], int row, char value)
{
for(int i{}; i<8; i++) {
if(sudokuBoard[i][row] == value) { return true;}
}
return false;
}
/* checkSquareMatches: returns true if any matches found in the same square.
* Otherwise returns false.
*/
bool checkSquareMatches(char sudokuBoard[][9], int col, int row, char value)
{
switch(col % 3) {
case 1:
col -= 1;
break;
case 2:
col -= 2;
break;
default:
break;
}
switch(row % 3) {
case 1:
row -= 1;
break;
case 2:
row -= 2;
break;
default:
break;
}
for(int i{col}; i<col+3; i++) {
for(int j{row}; j<row+3; j++) {
if(sudokuBoard[i][j] == value) {
return true;
}
}
}
return false;
}
/* checkCandidateforCell: returns true if value is a legitimate candidate for
cell[col][row].
Otherwise returns false;
*/
bool checkCandidateforCell(char sudokuBoard[][9], int col, int row, char value)
{
if(!checkCellRangesAndEmptiness(sudokuBoard, col, row)) { return false; }
if(checkColMatches(sudokuBoard, col, value)) { return false; }
if(checkRowMatches(sudokuBoard, col, value)) { return false; }
if(checkSquareMatches(sudokuBoard, col, row, value)) { return false; }
return true;
}
| |