I am building a Sudoku game in React, the last function I wrote would make the board. It makes an empty Board (2D Array filled with zeros), solves the board, then takes some random values out to make it a playable Sudoku. The problem is that making the 2D Zeros Array is giving me a 2D Array filled with random numbers. It is crazy I know, but it is making me crazy that I can't figure out what the problem is. Code snippets that I've used:
let emptyBoard = [
[ 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
];
let emptyBoard = new Array(9).fill(new Array(9).fill(0));
let emptyBoard = [];
for (let i = 0; i < 9; i++) {
emptyBoard.push([]);
for (let j = 0; j < 9; j++) {
emptyBoard[i].push(0);
}
}
The complete function is as follows:
makeBoard() {
let emptyBoard = [
[ 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
];
console.log(emptyBoard);
let { result, cells } = this.solveAndShuffle(emptyBoard);
if (result) {
let shuffledKeys = this.shuffle([ ...Array(81).keys() ]);
for (let key of shuffledKeys) {
const subgrid = Math.floor(key / 9);
const cell = key % 9;
const cellValue = cells[subgrid][cell];
cells[subgrid][cell] = 0;
const solutions = this.cellSolutions(subgrid, cell, cells);
if (solutions.length !== 1 && solutions.length !== 2) {
cells[subgrid][cell] = cellValue;
}
}
const immutable = this.immutableCells(cells);
this.setState({
cells: cells,
immutable: immutable,
wrongCells: new Array(9).fill(new Array(9).fill(false)),
causingError: new Array(9).fill(new Array(9).fill(false)),
solved: false
});
} else {
alert('Something wrong happend while trying to make a board!');
}
}
I even deployed it with the console.log on Github Pages if anyone wants to check it online it is on Sudoku JS, you can call the function by pressing "New".
And the code is hosted on Github
I am thankful for anyone who could provide help ♥