Home >Web Front-end >JS Tutorial >Web page example of Sudoku problem solving algorithm implemented in Javascript_javascript skills

Web page example of Sudoku problem solving algorithm implemented in Javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:19:561544browse

1) When we get a question, we will first conduct a preliminary sorting and analysis of the data based on the conditions we already know.

It is equivalent to filling out all the "determined items" in the 9-square grid and marking the "possible options".

function refreshStat()

2) After that, thinking will enter the guessing/verifying cycle stage.

In the 9-square grid, you can try the "possible options" to verify whether they violate the existing conditions.

For every new branch, the final result is nothing more than two, answer/error.

Copy code The code is as follows:
While (true) {
var a = setone ();
var b=refreshStat();
if(!a||b){ //If a==false or b==ture, you can break out of the loop
break;
}
     }

The actual thinking process of the human brain also involves traversing branches with fewer options first.
So, the program implementation is also determined point/2-branch/3-branch/....

3) When all the paths are searched, the answer is not the only one, which is contrary to the purpose of the Sudoku game.

The following part is the entire code. For the convenience of reading, the debugging information has not been deleted.

Copy code The code is as follows:


 
  数独解题程序

  <script><br>   function keygo(evt,obj){<br>       key = window .event?evt.keyCode:evt.which;<br>       var next=obj.tabIndex ;<br>       var inputs=document.getElementsByTagName("input");<br>       if (key==38){//↑<br>           if (next -9>=0 ) {<br>               inputs[next-9].select()<br>           }<br>       }<br>       if (key==40){//↓<br>           if (next +9<81 ) {<BR> inputs[next+9].select()<BR> }<BR> }<BR> if (key==37){//←<BR> if (next -1>=0 ) {<br>               inputs[next-1].select()<br>           }<br>       }<br>       if (key==39){//→<br>           if(next+1<81)inputs[next+1].select();<BR> }<BR> }<BR> </script>
 





可以文本拷贝到下框中后点粘贴,从左到右从上往下的81个数字序列,未填为0,中间非数字字符将忽略



  <script><br>   var maxRow =9;<br>   var maxCol = 9;<br>   var strTbody = ["<table id='sodukuTable' border='0'><tbody>"];<br>   for(var i = 0; i < maxRow; i++){<BR> strTbody.push("<tr>");<br>     for(var j = 0; j < maxCol; j++){<BR> strTbody.push("<td style='border-left:"+(j%3==0?1:0)<BR> +"px solid black ;border-right:"+(j%3==2?1:0)<BR> +"px solid black;border-top:"+(i%3==0?1:0)<BR> +"px solid black;border-bottom:"+(i%3==2?1:0)+"px solid black;' ><input style='width:20px;' tabindex='"+(i*9+j)<BR> +"'onclick='check(this);' onKeyUp='return keygo(event,this)'type='text' id='input"+(i*9+j)+"'name='n"+(i*9+j)+"'value='"+i+j+"' ></td>");<br>     }<br>    strTbody.push("</tr>"); <br>   }<br>   strTbody.push("</tbody></table>"); <br>   var sTbody = ["<table border='1'><tbody>"];<br>   for(var i = 0; i < maxRow; i++){<BR> sTbody.push("<tr>");<br>     for(var j = 0; j < maxCol; j++){<BR> sTbody.push("<td style='border-left:"+(j%3==0?1:0)<BR> +"px solid black ;border-right:"+(j%3==2?1:0)<BR> +"px solid black;border-top:"+(i%3==0?1:0)<BR> +"px solid black;border-bottom:"+(i%3==2?1:0)+"px solid black;'><div style='width:25px;height:25px' id='status"+(i*9+j)+"'name='div"+i+j+"' ></div></td>");<br>     }<br>    sTbody.push("</tr>"); <br>   }<br>   sTbody.push("</tbody></table>"); <br>   var obj = document.getElementById("sodukuTable");<br>   obj.innerHTML = strTbody.join("");<br>   var obj2 = document.getElementById("statusDiv");<br>   var grid=[    <br>    [5, 7, 0, 1, 2, 0, 0, 0, 0],<br>    [0, 0, 0, 0, 0, 0, 0, 0, 0],<br>    [0, 0, 6, 7, 0, 0, 0, 8, 0],<br>    [3, 0, 4, 0, 0, 9, 0, 7, 0],<br>    [0, 2, 0, 0, 7, 0, 0, 5, 0],<br>    [0, 1, 0, 3, 0, 0, 9, 0, 2],<br>    [0, 8, 0, 0, 0, 2, 1, 0, 0],<br>    [0, 0, 0, 0, 0, 0, 0, 0, 0],<br>    [0, 0, 0, 0, 5, 4, 0, 6, 3]];<br>   var candidatNum=[];<br>   var columns=[];<br>   var rows=[];<br>   var blook=[];<br>   var papers=0;<br>   var discards=0;<br>   var success=false;<br>   var steps = new Array();<br>   var log1 = document.getElementById("statusDiv"); <p>function Step(current1,arrys){<br>        this.temp1=new Array();<br>        this.step=[arrys[0],arrys[1],arrys[2]];<br>        for (var i = 0; i < 9; i++)<BR> {<BR> this.temp1[i]=new Array();<BR> for (var j = 0; j < 9; j++)<BR> {<BR> this.temp1[i][j]=current1[i][j];<BR> }<BR> }<BR>}<BR>out(grid);<BR>init();</P> <P>function push( current1, i, j, n) {<BR> var s = new Step(current1, [ i, j, n ]);<BR> steps.push(s);<BR>}<BR>function pop(){<BR> var step = steps.pop();<BR> discards ++;<BR> grid=step.temp1;<BR> grid[step.step[0]][step.step[1]] = step.step[2];<BR> var timeline = document.getElementById('PaperList');<BR> timeline.value += ('discard: ['+discards+']:['+papers+']\n');<BR> timeline.scrollTop = timeline.scrollHeight;<BR> return step;<BR>}<br><br>function check(obj){<BR> if(obj.value==0)return;<BR> for(var i=0;i<9;i++){<BR> for(var j=0;j<9;j++){<BR> var text = document.getElementById("input"+(i*9+j));<BR> if(text.value==obj.value){<BR> text.style.background="green";<BR> }else{<BR> text.style.background="";<BR> }<BR> }</P> <P> }</P> <P>}<BR>function CheckNumInput(array,num, x, y) {<BR> // 目标:<BR> // 冲突检查 参数 array:矩阵 num:检测值 x/y:检测位置<BR> // 行列宫均无冲突,return true;<BR> // 发现冲突,return false;<BR> if (((rows[x] & (1 << num)) == 0) && (columns[y] & (1 << num)) == 0<BR> && (blook[parseInt(x / 3) * 3 + parseInt(y / 3)] & (1 << num)) == 0) {<BR> return true;<BR> }<BR> return false;<BR>}</P><P>function out(array){<BR> var result=true;<BR> for (var i = 0; i < 9; i )<BR> {<BR> for (var j = 0; j &lt 9; j )<BR> =0) result = false; > // Traverse the matrix to see if it can be simply refreshed or the error can be found. <BR> for (var i = 0; i < 9; i ) {<BR> for (var j = 0; j < 9 ; j ) {<BR>                                                                                                                                                                                                     // (grid[i][j] == 0 && candidatNum[i][j][0] == 0) >> No candidate number, Something went wrong <br>                                                                                                                                                                                                                                                            ,j) >> Check whether this number is logical <br> // Determine that there are no candidate numbers || The last candidate number does not meet the logical conditions, fall back from here or return an error <br> if (grid[i] [j] == 0 && candidatNum[i][j][0] == 0 || ][10],i,j))) {<br>                                                                                                                             If (steps.length>0 ) {// Retreat </p> <p> POP (); // The current label has been proven to be logical errors, abandoned <br> Return true; <br>} else {<br> if (! Success) {<br> Alert (Alert (Alert (Alert "The stack is empty and ends!");    //题目出错,结束<br>                            }<br>                        return false;<br>                    }<br>            }<br>            if (candidatNum[i][j][0] == 1) {              //唯一选择<br>                grid[i][j] = candidatNum[i][j][10];       //  更新矩阵<br>                refreshStat3(candidatNum[i][j][10],i,j);  //  更新行列宫<br>                candidatNum[i][j][0] = 0;                 //  标记已选<br>                result = true;<br>                continue;<br>            }<br><br>        }<br>    }<br>    if (result == false) { //对于(candidatNum[i][j][0] != 1)的情况,进行筛选<br>        return choose();<br>    }<br>    return result;<br>}<br>function refreshStat3( num, x, y) {   //  更新行列宫<br>        rows[x] |= 1<<num;<BR> columns[y] |= 1<<num;<BR> blook[parseInt(x / 3) * 3 + parseInt(y / 3)] |= 1 << num ;</P> <P>}<BR>/*********************<BR> * 矩阵 数据分析<BR> * 统计 剩余可选项<BR> *********************/<BR>function refreshStat(){<BR> var over = true;<BR> // 目标:<BR> // 分解行/列/宫<BR> for (var i = 0; i < 9; i++) {<BR> rows[i] = 0; //行<BR> columns[i] = 0; //列<BR> blook[i] = 0; //宫<BR> for (var j = 0; j < 9; j++) {<BR> if (grid[i][j] != 0) {<BR> rows[i] |= 1 << grid[i][j];<BR> } else {<BR> rows[i] &= ~(1 << grid[i][j]);<BR> }<BR> if (grid[j][i] != 0) {<BR> columns[i] |= 1 << grid[j][i];<BR> } else {<BR> columns[i] &= ~(1 << grid[j][i]);<BR> }<BR> if (grid[parseInt(i / 3) * 3 + parseInt(j / 3)][i % 3 * 3 + j % 3] != 0) {<BR> blook[i] |= 1 << grid[parseInt(i / 3 )* 3 + parseInt(j / 3)][i % 3 * 3 + j % 3];<BR> }<BR> }<BR> }<BR> // 目标:<BR> // 遍历矩阵,进行候选标记candidatNum[i][j][0]<BR> // candidatNum[i][j][0] = 0; >>>>    已有确定值<br>    //      candidatNum[i][j][0] = k;    >>>>    可能值数目<br>    //      candidatNum[i][j][1] = 987654321x    2进制数位表示的可选数字<br>    for (var i = 0; i < 9; i++) {<BR> for (var j = 0; j < 9; j++) {<BR> if (grid[i][j] != 0) {<BR> candidatNum[i][j][0] = 0;<BR> continue;<BR> }<BR> var size = 0;<BR> over = false;<BR> for (var k = 1; k < 10; k++) {<BR> if (CheckNumInput(grid, k, i, j)) {<BR> candidatNum[i][j][1] |= 1 << k;<BR> candidatNum[i][j][10] = k;<BR> over = false;<BR> size++;<BR> } else {<BR> candidatNum[i][j][1] &= ~(1 << k);<BR> }<BR> }<BR> candidatNum[i][j][0] = size; //标记剩余选项数目<BR> }<BR> }<BR> return over;<BR>}</P><P>function calculate(){ //Function entry<BR> //Read data<BR> var start=new Date();<BR> for (var i = 0; i < 9; i )<BR>                                                                                                                                                        ​ grid[i ][j]=parseInt(text.value);<BR> }<BR> }<BR><BR> //Refresh the grid <BR> refreshStat();<BR> out(grid);<br> / /Calculate matrix<br> while(true){<BR> var a=setOne();<BR> var b=refreshStat();<BR> if(!a||b){ //If a==false Or b==ture, you can break out of the loop <BR>         break; ) "ms");<BR> success = true;<BR> //Computation ends<BR><BR> //Verify whether the answer is unique<BR> if (papers != discards){<BR> if (steps. length>0) {//Back<br> pop(); // Current label is discarded<br> //Calculate matrix <br> while(true){<br> var a=setOne();<br> var var b=refreshStat();<br> if(!a||b){ //If a==false or b==ture, you can break out of the loop<br> break;<br> }<br>                }<br>               if (b) {<br>                                                                                                                                                                                                                    if (b) {<br>                       alert("The answer is not unique! Record! " ); //The only answer<br> }<br> } else { <br> alert("Error ended!");<br>                return false;<br>            }<br>    }<br>}<br>function clearGrid(){<br>    for (var i = 0; i < 9; i++){<BR> for (var j = 0; j < 9; j++){<BR> grid[i][j]=0;<BR> document.getElementById("input"+(i*9+j)).value=grid[i][j];<BR> }<BR> }<BR> out(grid);<BR>}<BR>function init(){<BR> for (var i = 0; i < 9; i++)<BR> { candidatNum[i]=new Array();<br><br> for (var j = 0; j < 9; j++)<BR> { candidatNum[i][j]=new Array();</P><P> for (var k = 0; k < 11; k )<BR> { candidatNum[i][j][k]=0;<BR> }<BR> }<BR> }<BR>} <BR>function choose() {<BR> //Goal:<BR> // Traverse the matrix and establish a search branch from the current position.<BR> var binarynode = false;<BR> for (var i = 0; i &lt ; 9; i ) {<BR> for (var j = 0; j < 9; j ) {<BR> // 2-way tree branch: <BR> // If there are two possibilities at a certain position, option 1 /Options 2 </> // The assumption is option 1, and the verification is performed. 2 options<BR> binarynode = true;<BR> var found = -1;<BR> for (var k = 1; k < 10; k ) {<BR> if ((candidatNum[i][j] [1] & (1 << k)) > 0) {<br>                                                                                          var timeline = document.getElementById('PaperList');<br>                 timeline.value = ('add papers:' papers ':' i ' ' j ' ' k 'n'); <br>                              push(grid, i, j, k); } else {<br> Found = k; <br>} <br>} <br>} <br> Grid [i] [j] = Found; <br> Candidatnum [i] [j] ][0] = 0; // Mark selected <br> on the current label var timeline = document.getElementById('PaperList');<br> timeline.value = ('TRY CURRENT:' i ' ' j ' ' found 'n');<br> timeline.scrollTop = timeline.scrollHeight;<br> return true;<br> }<br> }<br> }<br> if (!binarynode) {<br> var timeline = document.getElementById('PaperList');<br> timeline.value = ('2-branch not found!n');<br> timeline.scrollTop = timeline.scrollHeight;<br> for (var i = 0; i < 9; i ) {<BR> for (var j = 0; j < 9; j ) {<BR> // 2-way tree search failed When , start the 3-way tree branch. As an extension, you can also start the 3-way tree branch: , and perform verification, and press option 2 to generate a new label <BR> if (candidatNum[i][j][0] == 3) {// There are 3 options <BR> var timeline = document.getElementById( 'PaperList');<BR> timeline.value = ('3-branch found!n');<BR> timeline.scrollTop = timeline.scrollHeight;<BR> binarynode = true;<BR> var found = -1; <BR> for (var k = 1; k < 10; k ) {<BR> if ((candidatNum[i][j][1] & (1 << k)) > 0) { If (Found & GT; 0) {<br> Papers; <br> VAR TIMELINE = DOCUMENT.GetelementByid ('PaperList'); '' j 'k' n '); <br> Timeline.scrolltop = Timeline.scrollheight; <br> Push (Grid, I, J, K); <br>} else {<br> Found = k; <br> }<br>                                                                                            <br> grid[i][j] = found;<br> candidatNum[i][j][0] = 0; // Mark selected on the current label <br> var timeline = document.getElementById('PaperList ');<br> timeline.value = ('TRY CURRENT:' i ' ' j ' ' found 'n');<br> timeline.scrollTop = timeline.scrollHeight;<br>             return true;<br>                                                                                                                    . 🎜>                                                                                                                                       a = gridstr.replace(/[^0-9]/g,'');<br> if(a.length!=81){<br> alert("Incorrect data format: n" gridstr);<br> return;<br> }<br> for (var i = 0; i < 9; i )<BR> {<BR> for (var j = 0; j < 9; j ){<BR> grid[i][j]=a.charAt(i*9 j);<BR> document.getElementById("input" (i*9 j)).value=grid[i][j];<BR> } <BR> }<BR> out(grid);<BR> papers = 0;<BR> discards = 0;<BR> success = false;<BR> steps = new Array();<BR>}<BR> </script>
It is recommended to use IE browser, F12 to enable debugging mode








Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn