Created
May 11, 2015 20:45
-
-
Save kopiro/e483b07aed2594d89771 to your computer and use it in GitHub Desktop.
Sudoku solver with backtracking
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
function getp(puzzle, x, y) { | |
var hash = {}; | |
for (var u = 0; u < 9; u++) hash[ puzzle[y][u] ] = 1; | |
for (var u = 0; u < 9; u++) hash[ puzzle[u][x] ] = 1; | |
for (var u = 0; u < 9; u++) hash[ puzzle[ 3*((y/3)|0) + ((u/3)|0) ][ 3*((x/3)|0) + (u%3) ] ] = 1; | |
var poss = []; | |
for (var i = 1; i <= 9; i++) if (!(i in hash)) poss.push(i); | |
return poss; | |
} | |
function sudoku(puzzle) { | |
var indicies = [], n = 0; | |
for (n = 0; n < 9*9; n++) if (puzzle[(n/9)|0][n%9] === 0) indicies.push({ v: n, p: null, i: 0}); | |
n = 0; | |
while (n < indicies.length) { | |
var c = indicies[n], y = (c.v/9)|0, x = c.v%9; | |
c.p = c.p || getp(puzzle, x, y); | |
if (c.i >= c.p.length) { | |
puzzle[y][x] = 0; | |
c.i = 0; c.p = null; | |
n--; | |
} else { | |
puzzle[y][x] = c.p[c.i++]; | |
n++; | |
} | |
} | |
return puzzle; | |
} |
Author
kopiro
commented
May 11, 2015
function getp(puzzle, x, y) {
var hash = {};
for (var u = 0; u < 9; u++) {
hash[ puzzle[y][u] ] =
hash[ puzzle[u][x] ] =
hash[ puzzle[ 3*((y/3)|0) + ((u/3)|0) ][ 3*((x/3)|0) + (u%3) ] ] = 1
}
var poss = [];
for (var i = 1; i <= 9; i++) if (!(i in hash)) poss.push(i);
return poss;
}
419 bytes solution
function sudoku(p) {
var f=[],a=function(p,d,e){var o=[],h={};
for(var u=0;++u<9;h[p[e][u]]=h[p[u][d]]=h[p[3*((e/3)|0)+((u/3)|0)][3*((d/3)|0)+(u%3)]]=1);
for(var i=10;--i>0;(i in h)?0:o.push(i));return o};
for(var n=0;++n<81;p[(n/9)|0][n%9]?0:f.push({v:n,p:0,i:0}));
for(var c,d,e,n=0,l=f.length;n<l;c=f[n],e=(c.v/9)|0,d=c.v%9,c.p=c.p||a(p,d,e),(c.i>=c.p.length)
?[p[e][d]=c.i=c.p=0,n--]:[p[e][d]=c.p[c.i++],n++]);return p}
(BTW, this is slower than the main solution)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment