Given a multi-dimensional array representing a board in Sudoku, the function should be able to return whether the sudoku is valid or not.
Examples:
var goodSudoku = [
[7,8,4, 1,5,9, 3,2,6],
[5,3,9, 6,7,2, 8,4,1],
[6,1,2, 4,3,8, 7,5,9],
[9,2,8, 7,1,5, 4,6,3],
[3,5,7, 8,4,6, 1,9,2],
[4,6,1, 9,2,3, 5,8,7],
[8,7,6, 3,9,4, 2,1,5],
[2,4,3, 5,6,1, 9,7,8],
[1,9,5, 2,8,7, 6,3,4]
];
var badSudoku = [
[1,1,1, 1,1,1, 2,2,2],
[5,3,9, 6,7,2, 8,4,1],
[6,1,2, 4,3,8, 7,5,9],
[9,2,8, 7,1,5, 4,6,3],
[3,5,7, 8,4,6, 1,9,2],
[4,6,1, 9,2,3, 5,8,7],
[8,7,6, 3,9,4, 2,1,5],
[2,4,3, 5,6,1, 9,7,8],
[1,9,5, 2,8,7, 6,3,4]
];
validSudoku(badSudoku); // false;
validSudoku(goodSudoku); // true;
Specific questions
- How can I improve my function? What am I doing bad/good?
- Is my algorithm efficient? Advice on it?
Here is my code
function validSudoku(data) {
var valid = true,
temp = [],
data,
side,
slot;
// Check wrong size
if (data[0].length !== data.length) valid = false;
// slot*slot
slot = Math.sqrt(data.length);
// Verifiy horizontal
data.forEach(function(arr) {
valid = valid && arr.every(function(val, i) { return arr.indexOf(i + 1) > -1; });
});
// Verifiy vertical lines
data.forEach(function(arr, i) {
temp = data.map(function(val) { return val[i]; });
valid = valid && arr.every(function(val, i) { return temp.indexOf(i + 1) > -1; });
});
// Verifiy boxes
for (var i = 0; i < slot; i++) {
data.forEach(function(val, e) {
side = val.slice(slot * i, slot * i + slot);
temp = temp.concat(side);
if ((e+1) % slot == 0 && e > 0) {
for (var j = 1; j <= data.length; j++)
if (temp.indexOf(j) < 0) valid = false;
temp = [];
}
});
}
return valid;
}
false
in the middle. If you finish the loop, returntrue
. \$\endgroup\$