Solve Sudoku Puzzles with Javascript Bitwise Operators

Erdoğan Bavaş
2 min readAug 18, 2020

In this project, we will produce a programmatic solution for simple sudoku puzzles. You can watch the speed code video above and access the codes here.

First, let me explain what Bitwise operators are and how they are used. It is explained very clearly in the MDN documents. These operators return a new value by performing the appropriate operation with the binary values of the elements they are used. Let’s give two examples and continue.

// 9 binary 1001
// 2 binary 0010
// | bitwise OR returns 0 if both digits are 0 otherwise returns 1
console.log(9 | 2); // 11 binary 1011
// & bitwise AND returns 1 if both digits are 1 otherwise returns 0 console.log(9 | 2); // 0 binary 0000

We create our index HTML file and simply add our CSS and Javascript files as usual. There is no complicated situation in the CSS part.

In our javascript file, we assign our main object to a variable named sudokuSolver. Sudoku is a game of 81 cells. We will put an input element for each cell, fill in these elements and reflect the solution to these inputs with a SOLVE button.

In our solve function, we define a variable where we take the registered numbers and the variables where we keep the values of rows, columns, squares of 9×9. When adding our numbers in cells to rows, columns, squares, take the power of 2 and merge with | operator. Because we want each digit to correspond to a number in a binary. All elements rows, columns and squares arrays are 9 digit binary number.

We start looking for the solution by calling the findNumber function recursively. We do a check at the start of this function and set a limit on the number of recursions. Then we check the probabilities for empty cells in each coordinate with a nested loop with the & operator. If there is only one element in the possibilities array, we find our value for this cell. We update the necessary variables on rows, columns and squares arrays and return the findNumber function. This process continues until it returns TRUE and a solution is found.

This will only find correct answers for simple sudoku puzzles. For sudokus that require complex methods, the solution script found may not be correct.

--

--