Question

Im making a script that solves a 3*3 sudoku. these would be a working answers:

123   312
231   123
312   231

As an input, I would give a 3*3 sudoku, where the zeros are blank spots. this one would work: 023 230 310

as an output, I would get: 123 231 312

However my script doesnt work. My input is called sq I have a function called findZero that searches for a zero I have a function called fill that removes the zero for a working number i have a function called checkRC (check row column) that scans for a working number

This would be a recursive script.

However, with this script I would get with the given input:

[0, 2, 3],
[2, 3, 0],
[3, 1, 0]

this output:

[1, 2, 3],
[2, 3, 0],
[3, 1, 0],

so it only changes it one time and then stops I think. I have no clue how to repair this!

This is my code:

var sq = [
    [0, 2, 3],
    [2, 3, 0],
    [3, 1, 0]
];
var x;
var y;

function findZero(square) {
    for (var i = 0; i < 3; i++) {
        for (var j = 0; j < 3; j++) {
            if (square[i][j] === 0) {
                x = i;
                y = j;
                return [x, y];
            }
        }
    }
    return [-1, -1];
}

function fill(square) {

    if (findZero(square)[0] == -1) {

        return square; }

      else {
        for (var w = 1; w < 4; w++) {
            if(checkRC(square,x,y,w) === true){
             square[x][y] = w;
                return square;


            }
        }
     }
}


var bool = true

 function checkRC(square, x, y, w) {

    for (var k = 0; k < 3&&bool; k++) {
        if (square[x][k] == w || square[k][y] == w) {
            bool = false;
            return bool;
          }
          else{
            bool = true;
            return bool;

        }
    }
}


console.log(fill(sq));

If you find a jsfiddle link easier:

http://jsfiddle.net/akqn7/

Thanks in advance!

Was it helpful?

Solution

So first you never called your function in recursive !

function fill(square) {

    if (findZero(square) === null) {
        return square;
    } else {
        for (var w = 1; w < 4; w++) {
            if (checkRC(square, x, y, w) === true) {
                square[x][y] = w;
                return fill(square);
            }
        }
    }
}    

Look how i placed return fill(); that's where your recursive needs to be

Your function checkRC was wrong too, here's the corrected version:

function checkRC(square, x, y, w) {

    var bool = true;

    for (var k = 0; k < 3 && bool; k++) {
        if (square[x][k] == w || square[k][y] == w) {
            bool = false;
            break;
        }
    }
    return bool;
}

I placed the bool inside the function and don't return directly the result because if it was false to the first number, it would stop.

See this fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top