Sudoku

This project was one of my first ideas to make after making my chess program. Coming up with the algorithm to fill in the 9x9 grid in the correct order was tricky and took a lot of creative thinking. My first attempts were failures. I could fill out about a third of the grid but then the program would hang. Eventually I came up with a method that did work. This program has three modules. First is the completed sudoku generator, second is anything related to the inputs, and the third module creates the DOM structure.

A sudoku grid must follow one simple rule. Each number from 1 - 9 must only appear once in its row, column, and box. I built a 9x9 2d array and placed an array in all of its positions that contained the numbers 1 - 9. Now I had a 9x9 array of arrays. I randomly picked a square from my 9x9 array and picked one of the numbers from it. I then removed that number from all the arrays in the rows, columns, and boxes so that I couldn't pick it again. I repeated this process until each squares array contained only one final number. This method worked 50 percent of the time. It was still possible for the program to get stuck doing this. It would need backtracking, but I went for the simpler option and just rerolled until we did get a working version.

Now I had my completed sudoku grid and I could use that to create a playable sudoku game. First I needed to generate the DOM structure. There was no writing it in HTML because I needed many many nodes. I created a helper function that would create a new div, assign it a class, and attach the div to a node. Then I simply created all the nodes I needed. I needed a 9x9 grid of course, and also I needed each cell in that grid to have within it a 3x3 grid. This 3x3 grid would be for making notes on the square. Then I made nodes for the big numbers that show up when the button is pressed. I also made nodes for all the buttons. Then I styled it all with CSS/Sass.

I made an interface module. Its job was to control the UI and display anything that needed to be displayed. I created event listeners for all the necessary buttons. I made a new game button and a solution button. I made the note mode. Obviously there was more to it than this, but I don't want to bore you too much with the details.

I feel like I did a pretty decent job on this project. The interface and create elements modules were done months after I had already made the sudoku grid generator. I feel like the later modules were a lot cleaner. If I redid the sudoku generator again, I think it would be a lot cleaner. Especially how I checked a row column and grid. I could do that with 1 double for loop now, instead of making like 18 unnecessary variables. Also the algorithm itself is a little confusing for even me to understand when I am looking back on it today. I think if I wrote the same program today, it would be much simpler to understand.