Copy codeThe Code is as follows:
<P> <input value = "Get New SuDoKu" type = "button" onclick = "onLoadTable ()" id = "refreshButton"/> </p>
<Table border = "1" style = "border-color: Red;" id = "mainTable">
<Tbody>
</Tbody>
</Table>
<Script type = "text/javascript" language = "javascript"> // <! [CDATA [
Var sudokuArray = [[], [], [], [], [], [], [], [], [], [];
Function onLoadTable ()
{
Do
{
SudokuArray = getNewArray ();
SudokuArray = getSudokuArray (sudokuArray );
}
While (! CheckArray (sudokuArray ))
// Document. getElementById ("result"). innerHTML = checkArray (sudokuArray );
Var table = document. getElementById ("mainTable ");
Table. removeChild (table. firstChild );
For (var I = 0; I <9; I ++)
{
Table. insertRow (I );
For (var j = 0; j <9; j ++)
{
Table. rows [I]. insertCell (j );
Table. rows [I]. cells [j]. innerHTML = sudokuArray [I] [j]; // Math. round (Math. random () * 8 + 1 );
SetStyle (I, j, table. rows [I]. cells [j]);
}
}
}
Function getSudokuArray (filledArray)
{
Var failed = false;
For (var I = 0; I <9; I ++)
{
For (var j = 0; j <9; j ++)
{
Var tempArray = getAvaildableArray (I, j, filledArray );
If (tempArray. length> 0)
{
FilledArray [I] [j] = tempArray [Math. round (Math. random () * (tempArray. length-1)];
}
Else
{
// Window. location. reload ();
}
}
}
Return filledArray;
}
Function checkArray (array)
{
For (var I = 0; I <9; I ++)
{
For (var j = 0; j <9; j ++)
{
If (array [I] [j] = undefined)
{
Return false;
}
}
}
Return true;
}
Function getAvaildableArray (rowIndex, cellIndex, array)
{
Var availdableArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
For (var n = 0; n <9; n ++)
{
If (! IsNaN (array [rowIndex] [n]) & array [rowIndex] [n]! = Undefined)
{
AvaildableArray [array [rowIndex] [n]-1] = NaN;
}
If (! IsNaN (array [n] [cellIndex]) & array [n] [cellIndex]! = Undefined)
{
AvaildableArray [array [n] [cellIndex]-1] = NaN;
}
}
Var rowStartIndex = Math. floor (rowIndex/3 );
Var cellStartIndex = Math. floor (cellIndex/3 );
For (var x = rowStartIndex * 3; x <rowStartIndex + 3; x ++)
{
For (var y = cellStartIndex * 3; y <cellStartIndex + 3; y ++)
{
If (! IsNaN (array [x] [y]) | array [x] [y]! = Undefined)
{
AvaildableArray [array [x] [y]-1] = NaN;
}
}
}
Var returnArray = [];
For (var m = 0; m <9; m ++)
{
If (! IsNaN (availdableArray [m])
{
ReturnArray. push (availdableArray [m]);
}
}
Return returnArray;
}
Function getNewArray ()
{
Return [[], [], [], [], [], [], [], [], [], [];
}
Function setStyle (rowIndex, cellIndex, cell)
{
Cell. height = "20 ";
Cell. width = "20 ";
If (cellIndex % 3 = 2)
{
Cell. style. borderRightColor = "red ";
}
If (cellIndex % 3 = 0)
{
Cell. style. borderLeftColor = "red ";
}
If (rowIndex % 3 = 2)
{
Cell. style. borderBottomColor = "red ";
}
If (rowIndex % 3 = 0)
{
Cell. style. borderTopColor = "red ";
}
}
//]> </Script>