javascript实现数独解法

生生把写过的java版改成javascript版,第一次写,很不专业,见谅。唉,我是有多闲。

代码如下:

var Sudoku = {
    init: function (str) {
        this.blank = [];
        this.fixed = [];
        this.cell = [];
        this.trials=[];
        for (i = 0; i < 81; i++) {
            var chr = str.charCodeAt(i);
            if (chr == 48) {
                this.cell[i] = 511;
                this.blank.push(i);
            } else {
                this.cell[i] = 1 << chr - 49;
                this.fixed.push(i);
            }
        }
    },
    showBoard: function () {
        var board = "";
        for (var i = 0; i < 81; i++) {
            if (i % 9 == 0) {
                board = board.concat("\n");
            }
            board = board.concat("[");
            for (var j = 0; j < 9; j++) {
                if ((this.cell[i] >> j & 1) == 1) {
                    board = board.concat(String.fromCharCode(j + 49));
                }
            }
            board = board.concat("]");
        }
        return board;
    },
    check: function () {
        var checkpoint = [0, 12, 24, 28, 40, 52, 56, 68, 80];
        for (var i in checkpoint) {
            var r, b, c;
            r = b = c = this.cell[checkpoint[i]];
            for (j = 0; j < 8; j++) {
                c ^= this.cell[this.getX(checkpoint[i])[j]];
                b ^= this.cell[this.getX(checkpoint[i])[8 + j]];
                r ^= this.cell[this.getX(checkpoint[i])[16 + j]];
            }
            if ((r & b & c) != 0x1FF) {
                return false;
            }
        }
        return true;
    },
    bitCount: function (i) {
        var n = 0;
        for (var j = 0; j < 9; j++) {
            if ((i >> j & 1) == 1)
                n++;
        }
        return n;
    },
    numberOfTrailingZeros: function(i){
        var n = 0;
        for (var j = 0; j < 9; j++) {
            if ((i >> j & 1) ==0)
                n++;
            else{
                break;
            }
        }
        return n;       
    },
    updateCandidates: function () {
        for (var i in this.fixed) {
            var opt = 0x1FF ^ this.cell[this.fixed[i]];
            for (var j = 0; j < 24; j++) {
                this.cell[this.getX(this.fixed[i])[j]] &= opt;
                //!notice
                if (this.cell[this.getX(this.fixed[i])[j]] == 0) {
                    //console.log("Error-0 candidate:"+x[this.fixed[i]][j]);
                    return false;
                }
            }
        }
        return true;
    },
    seekUniqueCandidate: function () {
        for (var bidx in this.blank) {
            var row = 0, col = 0, box = 0;
            for (i = 0; i < 8; i++) {
                row |= this.cell[this.getX(this.blank[bidx])[i]];
                box |= this.cell[this.getX(this.blank[bidx])[8 + i]];
                col |= this.cell[this.getX(this.blank[bidx])[16 + i]];
            }
            if (this.bitCount(this.cell[this.blank[bidx]] & ~row) == 1) {
                this.cell[this.blank[bidx]] &= ~row;
                continue;
            }
            if (this.bitCount(this.cell[this.blank[bidx]] & ~col) == 1) {
                this.cell[this.blank[bidx]] &= ~col;
                continue;
            }
            if (this.bitCount(this.cell[this.blank[bidx]] & ~box) == 1) {
                this.cell[this.blank[bidx]] &= ~box;
            }
        }
    },
    seekFilledable: function () {
        this.fixed = [];
  var _del=[];
        for (var i in this.blank) {
            if (this.bitCount(this.cell[this.blank[i]]) == 1) {
                this.fixed.push(this.blank[i]);
                //console.log("fixed:"+this.blank[i]+"=>"+this.cell[this.blank[i]]);
                //this.blank.splice(i, 1);//to delete it in the loop would cause bug
    _del.push(i);
            }
        }
  while(_del.length>0){
   this.blank.splice(_del.pop(), 1);
  }
    },
    seekMutexCell: function () {
        var two = [];
        for (var n in this.blank) {
            if (this.bitCount(this.cell[this.blank[n]]) == 2) {
                two.push(this.blank[n]);
            }
        }
        for (var i = 0; i < two.length; i++) {
            for (var j = i + 1; j < two.length; j++) {
                if (this.cell[two[i]] == this.cell[two[j]]) {
                    var opt = ~this.cell[two[i]];
                    if (parseInt(two[i] / 9) ==parseInt(two[j] / 9)) {
                        for (n = 0; n < 8; n++) {
                            this.cell[this.getX(two[i])[n]] &= opt;
                        }
                    }
                    if ((two[i] - two[j]) % 9 == 0) {                       
                        for (n = 8; n < 16; n++) {
                            this.cell[this.getX(two[i])[n]] &= opt;
                        }
                    }
                    if ((parseInt(two[i] / 27) * 3 + parseInt(two[i] % 9 / 3)) == (parseInt(two[j] / 27) * 3 + parseInt(two[j] % 9 / 3))) {
                        for (n = 16; n < 24; n++) {
                            this.cell[this.getX(two[i])[n]] &= opt;
                        }
                    }
                    this.cell[two[j]] = ~opt;
                }
            }
        }
    },
    basicSolve: function () {
        do {
            if (!this.updateCandidates(this.fixed)) {
                this.backForward();
            }
            this.seekUniqueCandidate();
            this.seekMutexCell();
            this.seekFilledable();
        } while (this.fixed.length != 0);
        return this.blank.length == 0;
    },   
    setTrialCell: function() {
        for (var i in this.blank) {
            if (this.bitCount(this.cell[this.blank[i]]) == 2) {
                var trialValue = 1 << this.numberOfTrailingZeros(this.cell[this.blank[i]]);
                var waitingValue = this.cell[this.blank[i]] ^ trialValue;
                //console.log("try:[" + this.blank[i] + "]->" + (this.numberOfTrailingZeros(trialValue) + 1) + "#" + (this.numberOfTrailingZeros(waitingValue) + 1));
                this.cell[this.blank[i]] = trialValue;               
                this.trials.push(this.createTrialPoint(this.blank[i], waitingValue, this.cell));
                return true;
            }
        }
        return false;
    },
    backForward: function() {
        if (this.trials.length==0) {
            console.log("Maybe no solution!");
            return;
        }
        var back = this.trials.pop();
        this.reset(back.data);
        this.cell[back.idx] = back.val;
        this.fixed.push(back.idx);
        //console.log("back:[" + back.idx + "]->" + (this.numberOfTrailingZeros(back.val) + 1));
    },
    reset: function(data) {
        this.blank=[];
        this.fixed=[];
        this.cell=data.concat();
        for (var i = 0; i < 81; i++) {
            if (this.bitCount(this.cell[i]) != 1) {
                this.blank.push(i);
            } else {
                this.fixed.push(i);
            }
        }
    },
    trialSolve: function() {
        while (this.blank.length!=0) {
            if (this.setTrialCell()) {
                this.basicSolve();
            } else {
                if (this.trials.length==0) {
                    //console.log("Can't go backforward! Maybe no solution!");
                    break;
                } else {
                    this.backForward();
                    this.basicSolve();
                }
            }
        }
    },
    play: function() {
        console.log(this.showBoard());
        var start = new Date().getMilliseconds();
        if (!this.basicSolve()) {
            this.trialSolve();
        }
        var end = new Date().getMilliseconds();
        console.log(this.showBoard());
        if (this.check()) {
            console.log("[" + (end - start) + "ms OK!]");
        } else {
            console.log("[" + (end - start) + "ms, cannot solve it?");
        }
  //return this.showBoard();
    },
    getX:function(idx){
        var neighbors=new Array(24);
        var box=new Array(0,1,2,9,10,11,18,19,20);
        var r=parseInt(idx/9);
  var c=idx%9;
  var xs=parseInt(idx/27)*27+parseInt(idx%9/3)*3;
        var i=0;
        for(var n=0;n<9;n++){
            if(n==c)continue;
            neighbors[i++]=r*9+n;
        }
        for(var n=0;n<9;n++){
            if(n==r)continue;
            neighbors[i++]=c+n*9;
        }
        for(var n=0;n<9;n++){
            var t=xs+box[n];
            if(t==idx)continue;
            neighbors[i++]=t;
        }
          return neighbors;
    },
 createTrialPoint:function(idx, val, board) {
        var tp = {};
        tp.idx = idx;
        tp.val = val;
        tp.data = board.concat();
        return tp;
 }
};
//Sudoku.init("000000500000008300600100000080093000000000020700000000058000000000200017090000060");
//Sudoku.init("530070000600195000098000060800060003400803001700020006060000280000419005000080079");
Sudoku.init("800000000003600000070090200050007000000045700000100030001000068008500010090000400");
Sudoku.play();

以上就是关于使用javascript实现数独解法的全部代码了,希望大家能够喜欢。

(0)

相关推荐

  • Go语言实现的最简单数独解法

    soduku.go 复制代码 代码如下: package main import (     "fmt" ) type node []int var sudokuMay [9][9]node var Sudoku = [9][9]int{     {0, 0, 0, 0, 0, 0, 8, 0, 0},     {0, 8, 2, 4, 0, 0, 0, 0, 0},     {1, 9, 0, 0, 6, 3, 0, 0, 0},     {0, 5, 0, 0, 8, 0, 7,

  • c++递归解数独方法示例

    复制代码 代码如下: #include<iostream> using namespace std; void init();void function(int m); int canplace(int row,int col,int c); void outputresult(); int a[9][9], maxm = 0; int main() {   init(); function(0);  return 0; } void init(){ int i, j; for(i = 0;

  • Python如何判断数独是否合法

    介绍 该数独可能只填充了部分数字,其中缺少的数字用 . 表示. 注意事项 一个合法的数独(仅部分填充)并不一定是可解的.我们仅需使填充的空格有效即可. 解体思路 将数独按照行.列和块进行预处理,然后分别判断是否合法. 利用Python的表达式推导,匿名函数和all函数可以很方便的进行处理. 代码 class Solution: # @param board, a 9x9 2D array # @return a boolean def isValidSudoku(self, board): ro

  • python实现数独算法实例

    本文实例讲述了python实现数独算法的方法.分享给大家供大家参考.具体如下: # -*- coding: utf-8 -*- ''' Created on 2012-10-5 @author: Administrator ''' from collections import defaultdict import itertools a = [ [ 0, 7, 0, 0, 0, 0, 0, 0, 0], #0 [ 5, 0, 3, 0, 0, 6, 0, 0, 0], #1 [ 0, 6, 2

  • Jquery数独游戏解析(一)-页面布局

    另外最近时间允许的情况下会移植到html5,暂定名称为H5sukudo主要目的也是练手. body的代码如下,页面主体使用main层来控制尺寸,main中包含两个层:canvas和tools,分别用来承载数独表格和辅助信息.tools层中嵌套了logo,level,lefts,timer,leftsg,btns,err共七个层,分别用来承载LOGO.游戏难度.剩余空格数.已用时间.剩余空格数明细.按钮和错误提示信息.tools层中的样式写在default.css样式文件中.canvas层.lev

  • Javascript 实现的数独解题算法网页实例

    1)当我们拿到一个题目时,首先会根据已经知道的条件,进行数据的初步整理和分析. 相当于填写出9宫格里,所有的"确定项",以及标记"可能选项". function refreshStat() 2)此后,思考会进入 猜测/验证 的循环阶段. 在9宫格中,可以对于"可能选项"进行尝试,验证是否违背现有条件. 每一个新的分支,最后的结果无非是两种,答案/出错. 复制代码 代码如下: while(true){                    var

  • java使用回溯法求解数独示例

    复制代码 代码如下: import java.util.Calendar;import java.util.Date; public class Matrix { private int matrix[][]; private long timeAfter=0;  private long timeBefore =0; public Matrix(int m[][]) {  matrix = new int[9][9];  for (int i=0; i<9 ; i++)   for(int j

  • JavaScript遍历求解数独问题的主要思路小结

    数独规则 数独游戏,经典的为9×9=81个单元格组成的九宫格,同时也形成了3×3=9个小九宫格,要求在81个小单元格中填入数字1~9,并且数字在每行每列及每个小九宫格中都不能重复. 数独技巧 直观法 候选数法 相关二十格:一个数字只与其所在行列及小九宫格的二十格相关 我的思路 精心设计了有效性判定函数,最多一次遍历81个小单元格就能做出方案的有效性判定. 同理设计了相关20格判定,一次0~9的循环就完成有效性判定. 用数组模拟堆栈,为搜索提供回溯信息. 利用对象具有map性质,来辅助判断方案的有

  • JQuery开发的数独游戏代码

    用了很多Jquery的插件,支持鼠标滚轮选数字.没有什么高深的技术点.工作原因很长时间没有更新了,具体代码都有些记不清了,欢迎大家来拍砖.截图:演示地址:http://demo.jb51.net/js/jsukudo/index.html下载地址:jsukudo20081110v0.3.0.5.zip 下载列表:http://code.google.com/p/jsukudo/downloads/list 用到的JS文件 文件名 出处 说明 blockUI.js http://malsup.co

  • javascript sudoku 数独智力游戏生成代码

    复制代码 代码如下: <p><input value="Get New SuDoKu" type="button" onclick="onLoadTable()" id="refreshButton" /></p> <table border="1" style="border-color: Red;" id="mainTable&qu

随机推荐