DEV Community

Discussion on: Bitmasks: A very esoteric (and impractical) way of managing booleans

Collapse
 
tsunwell profile image
tsunwell

I found your post long after it has been created, while I was looking for answer about bitwise operation.
I have a very good subject to use it.
I'm working on a personnal tool to play Soduku. It is a HTML, Javascript and CSS based tool.
In Sudoku game, the purpose is to complete a 9X9 cells grid, so the same digit exists only once in each row, column and 3X3 box. It is important to be able to control if a digit can be set at a specific place.
Classical control is quite complex, because you have to check every cell in the row, the column and the box hosting your target at least 3 loops with 9 steps each.
Using bits make things much easier : you just have to compute one value for each row, one for each column and one for each box of the grid, creating a binary digit corresponding (value 1) to the position of the possible digits. For example, if a row contains 3 an 8, the digit for that row is 101111011.
All 3 digits for a cell can be calculated in the same step of the loop.
For a cell, an simple AND on the three digits (row, column and box) to which belong the cell gives the possible values.
When a value is set, it is easy to update the corresponding digit in the 3 arrays, and then to check for next turns.
Thnaks for initial post and answers ...

Collapse
 
somedood profile image
Basti Ortiz • Edited

Honestly, I should be the one thanking you. What a brilliant use of bitmasks! Thanks for showing me this example. It really started my turning my gears for possible uses of bitmasking.