Friday, November 23, 2007

Sudoku Solver Progress, cntd.

My plans for "Black Friday" fell through, so I decided to spend some time optimizing and tweaking my Javascript code for my Sudoku solution testing piece. It's considerably smaller, thanks to a pair of for loops. It's also leaner and uses less processing because it doesn't bother to check the columns if it finds a problem in the rows.


// NAME: sudoku.js
// AUTHOR: Jonah Chanticleer
// VERSION: 2007.11.23
// LICENSE: Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

function checkRows(S) {

var sumOfRow = 0;
var x = 0;

for (x=0; x<9; x++) {
sumOfRow = S[x][0] + S[x][1] + S[x][2] + S[x][3]
+ S[x][4] + S[x][5] + S[x][6] + S[x][7] + S[x][8];
if (sumOfRow != 45) return false;
}

return true;
}

function checkCols(S) {

var sumOfCol = 0;
var x = 0;

for (x=0; x<9; x++)
{
sumOfCol = S[0][x] + S[1][x] + S[2][x] + S[3][x]
+ S[4][x] + S[5][x] + S[6][x] + S[7][x] + S[8][x];
if (sumOfCol != 45) return false;
}

return true;
}

function testSolution(S) {

var valid = false;

valid = checkRows(S);
if (valid == true) valid = checkCols(S);

return valid;
}