最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript Sudoku - Checking Rules - Stack Overflow

programmeradmin0浏览0评论

I'm working on a javascript sudoku, and as far as validation of input goes, I'm stumped. As each value is entered into the sudoku table, I have an onkeyup triggering a function which I am attempting to use to make sure that no value enters a row/column/box where such a value already exists. This is my first time attempting such a project, so I apologize in advance for the noob code.

Here's what I've got so far:

function myFunction(row) {
var x = 0;
var arraySolution = [
    [x, x, 4, 5, x, 3, x, 7, x],
    [x, x, x, x, x, x, 3, 1, x],
    [3, 5, x, x, x, 9, 2, x, x],
    [x, x, x, x, 2, x, 9, 3, 7],
    [6, x, 9, x, x, x, 4, x, 8],
    [4, 7, 2, x, x, x, x, x, x],
    [x, x, 1, x, x, x, x, 5, 2],
    [x, 4, 5, x, x, x, x, x, x],
    [x, 6, x, 8, x, 1, 7, x, x]
];

var num = row.innerHTML; //get its innerHTML
num = parseInt(num, 10);
if (num < 1 || num > 9) {
    row.innerHTML = "";//clear it if num is not what you expect
    alert("Please Enter a Number Between 1 and 9.");
}


//Checks Row
for (var b = 0; b < 9; b++) {
    if (num != arraySolution[0][b]) {
        console.log("This is a valid input");
        b++;
    }
    else if (num = arraySolution[0][b]) {
        alert("this is an invalid input");

        row.innerHTML = "";
    }
}
}

I know that using x as a placeholder is probably not the best plan, but at this point it is mostly for testing purposes so values being input wont exist before the testing starts. Where I attempt to check row, I'm obviously trying to loop through the array at indexes (0,0) -> (0,8) and check that no value exists twice in that row. I had this working to check a single row, but seem to have broken it while attempting to add more rows to check.

A brief example of what I was trying to check multiple rows (I pletely understand what I need to be doing as far as actual sudoku logic, but I cannot get this thing to validate)

    //Checks Row
for (var b = 0; b < 9; b++) {
    if ((num != arraySolution[0][b]) || (num != arraySolution[1][b])) {
        console.log("This is a valid input");
        b++;
    }
    else if ((num = arraySolution[0][b]) || (num != arraySolution[1][b])){
        alert("this is an invalid input");
        row.innerHTML = "";
    }
}

I'm working on a javascript sudoku, and as far as validation of input goes, I'm stumped. As each value is entered into the sudoku table, I have an onkeyup triggering a function which I am attempting to use to make sure that no value enters a row/column/box where such a value already exists. This is my first time attempting such a project, so I apologize in advance for the noob code.

Here's what I've got so far:

function myFunction(row) {
var x = 0;
var arraySolution = [
    [x, x, 4, 5, x, 3, x, 7, x],
    [x, x, x, x, x, x, 3, 1, x],
    [3, 5, x, x, x, 9, 2, x, x],
    [x, x, x, x, 2, x, 9, 3, 7],
    [6, x, 9, x, x, x, 4, x, 8],
    [4, 7, 2, x, x, x, x, x, x],
    [x, x, 1, x, x, x, x, 5, 2],
    [x, 4, 5, x, x, x, x, x, x],
    [x, 6, x, 8, x, 1, 7, x, x]
];

var num = row.innerHTML; //get its innerHTML
num = parseInt(num, 10);
if (num < 1 || num > 9) {
    row.innerHTML = "";//clear it if num is not what you expect
    alert("Please Enter a Number Between 1 and 9.");
}


//Checks Row
for (var b = 0; b < 9; b++) {
    if (num != arraySolution[0][b]) {
        console.log("This is a valid input");
        b++;
    }
    else if (num = arraySolution[0][b]) {
        alert("this is an invalid input");

        row.innerHTML = "";
    }
}
}

I know that using x as a placeholder is probably not the best plan, but at this point it is mostly for testing purposes so values being input wont exist before the testing starts. Where I attempt to check row, I'm obviously trying to loop through the array at indexes (0,0) -> (0,8) and check that no value exists twice in that row. I had this working to check a single row, but seem to have broken it while attempting to add more rows to check.

A brief example of what I was trying to check multiple rows (I pletely understand what I need to be doing as far as actual sudoku logic, but I cannot get this thing to validate)

    //Checks Row
for (var b = 0; b < 9; b++) {
    if ((num != arraySolution[0][b]) || (num != arraySolution[1][b])) {
        console.log("This is a valid input");
        b++;
    }
    else if ((num = arraySolution[0][b]) || (num != arraySolution[1][b])){
        alert("this is an invalid input");
        row.innerHTML = "";
    }
}
Share Improve this question asked Oct 26, 2015 at 13:57 Jeremy StoneJeremy Stone 3504 gold badges12 silver badges30 bronze badges 5
  • 4 = and == are two different things... – Niet the Dark Absol Commented Oct 26, 2015 at 14:18
  • do you want a fix for your code or some other hint for general sudoku validation? – Carlo Moretti Commented Oct 26, 2015 at 14:42
  • @Onheiron I'm just looking to find out how I can make the code I have for checking rows work for more than a single row. With that I could ideally work with it and figure out how to do the same for colums/boxes. However the code I do have doesn't seem to be working, but I feel like my logic may be close. – Jeremy Stone Commented Oct 26, 2015 at 14:49
  • I'm asking because you may want to consider a more problem specific data structure for your checking matrix. Something like var matrix = { 1:{ "cols":[2, 5, 7], "rows":[1, 6, 8], "boxes":[2, 6, 7] }, 2:{...} ... } Where you store for each digit the list of columns, rows and boxes where it appears, then you can simply do if(matrix[input].rows.indexOf(currentRow) >= 0) to check if already exists in a row. – Carlo Moretti Commented Oct 26, 2015 at 15:04
  • @Onheiron would you happen to have any links to look into this? I haven't thought of it this way – Jeremy Stone Commented Oct 26, 2015 at 15:12
Add a ment  | 

2 Answers 2

Reset to default 4

You can use this function to validate a solution :

// returns true if arraySolution is valid, false otherwise
function valid(arraySolution) {
    for (var y = 0; y < 9; ++y) {
        for (var x = 0; x < 9; ++x) {
            var value = arraySolution[y][x];

            if (value) {
                // Check the line
                for (var x2 = 0; x2 < 9; ++x2) {
                    if (x2 != x && arraySolution[y][x2] == value) {
                        return false;
                    } 
                }

                // Check the column
                for (var y2 = 0; y2 < 9; ++y2) {
                    if (y2 != y && arraySolution[y2][x] == value) {
                        return false;
                    } 
                }

                // Check the square
                var startY = Math.floor(y/3)*3;
                for (var y2 = startY; y2 < startY + 3; ++y2) {
                    var startX = Math.floor(x/3)*3;
                    for (x2 = startX; x2 < startX + 3; ++x2) {
                        if ((x2 != x || y2 != y) && arraySolution[y2][x2] == value) {
                            return false;
                        }
                    }
                }
            }
        }
    }

    return true;
}

jsBin demo

var x = 0, map = [
  [x, x, 4, 5, x, 3, x, 7, x],
  [x, x, x, x, x, x, 3, 1, x],
  [3, 5, x, x, x, 9, 2, x, x],
  [x, x, x, x, 2, x, 9, 3, 7],
  [6, x, 9, x, x, x, 4, x, 8],
  [4, 7, 2, x, x, x, x, x, x],
  [x, x, 1, x, x, x, x, 5, 2],
  [x, 4, 5, x, x, x, x, x, x],
  [x, 6, x, 8, x, 1, 7, x, x]
];


// This is what the user played
// after every user input update the "user" object.
var user = {};


function numberExists() {

  var err = [];

  for(var r=0; r<9; r++){ // iterate map rows

    if(map[r][user.cell] === user.num){ // current row, specific cell == Match?
      err.push(user.num +" exists in Row"+ r +" Cell"+ user.cell);
    }

    if(r === user.row){  // Is this row selected by the user?
       for(var c=0; c<9; c++){ // Iterate all cells of this row
          if(map[r][c] === user.num){ // Match?
             err.push(user.num +" exists in Row"+ r + " Cell"+ c);
          }
       }
    }

  }

  if(err.length){
    console.log( err.join(" and ") );
  } else { // No errors
    console.log( "GOOD! Row"+ user.row  +" Cell"+ user.cell );
  }

}

// TEST /////
user.row  = 4;
user.cell = 3;
user.num  = 8;
numberExists(); // Trigger search!

will trigger (in the above example using r4, c3, n8)

"8 exists in Row4 Cell8 and 8 exists in Row8 Cell3"

发布评论

评论列表(0)

  1. 暂无评论