Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Basic Sudoku Solver
<html>
<head>
<meta charset="utf8">
<meta content="width=device-width, user-scalable=no" name="viewport"/>
<script>
$$=function(sel){return [].slice.call(document.querySelectorAll(sel))}
function formSolve(){
var grid=(new Grid($$('input').map(function(e){return +e.value}))).solve();
$$('input').forEach(function(input,i){
input.title=grid.grid[i];
if(grid.grid[i].length==1)input.value=grid.grid[i][0]
})
}
function makeForm(){
var form=""
for(var i=0;i<9*9;i++)
form+=(i%9?'':'<tr>')+'<td><input type="number" onkeyup="formSolve()"></td>'+((i+1)%9?'':'</tr>')
document.forms[0].innerHTML='<table>'+form+'</table>';
}
function Grid(grid){
this.grid=[];
for(var i=0;i<9*9;i++)
this.grid[i]=grid[i]?[grid[i]]:[1,2,3,4,5,6,7,8,9]//0 mean every possibilities
this.solve=function(){
var minus=function(array,vals){
return (vals.constructor==Array?vals:[vals]).forEach(function(val){
var i=array.indexOf(val);
if(i!=-1)array.splice(i,1);
});
}
for(var prev_str;JSON.stringify(this.grid) != prev_str;){
prev_str=JSON.stringify(this.grid);//backup
this.grid=this.grid.map(function(possibilities,p){
if(possibilities.length==1)return possibilities;//already solved
var exclu=possibilities.slice();//will lose non exclusives one
for(var i=0;i<9;i++){
[(p-(p%9))+i,(p%9)+(i*9),(p-p%27)+(p-p%3)%9 + (i%3)+(0|i/3)*9]
.forEach(function(pos,b,a){//foreach rows,collumns,blocs
if(pos==p)return;//we don't compute ourself
//remove existing solved blocs from possibilities
if(this.grid[pos].length==1)
minus(possibilities,this.grid[pos]);
//check if i'm the only one to hold a possibility
minus(exclu,this.grid[pos]);
},this)
}
return exclu.length==1?exclu:possibilities;
},this);
}
return this;
}
}
</script>
<style>
*{margin:0;padding:0;}
table{width:100%;height:100%;border-spacing:0;}
td{border:1px solid #DDD;}
td:nth-child(3n){border-right:2px solid #000;}
tr:nth-child(3n) td{border-bottom:2px solid #000;}
input{width:100%;height:100%;font-size:2em;border:none;text-align: center;}
</style>
</head>
<body onload="makeForm()">
<form onsubmit="formSolve();return false;"></form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.