15 June 2024 - 3 min read

Creating a Sudoku Generator

Creating a Sudoku Generator

Introduction

I have always liked solving sudokus since I was young, however the interest in creating them myself was sparked easter of 2024, when my girlfriend and I were spending some time at the family cabin without much else to do. Initially I thought it would be a simple project as it on the surface does not seem as complex due to the nature of how it works. However, as I started to dig into how a sudoku is created, I quickly discovered there was a lot more to it. This article will take you through my process and what you may want to do differently, and what could be expanded upon.

How does a Sudoku work?

A Sudoku is a logic-based, combinatorial number-placement puzzle. The objective is to fill a 9×9 grid with digits so that each column, each row, and each of the nine 3×3 subgrids that compose the grid contain all of the digits from 1 to 9. The puzzle setter provides a partially completed grid, which for a well-posed puzzle has a single solution. The simplest approach when creating a sudoku is to start with a completed grid, and then remove numbers until you have the desired difficulty level. However, the difficulty comes from the fact that it should be solved without guessing, which I will go into later as to why that is more difficult to accomplish.

Creating a sudoku solver

In order to create a sudoku, we first need a simple solver. The solver will fill out the grid in a way that allows for all numbers to be placed correctly. This means no numbers can be repeated horizontally, vertically or in the 3x3 grid. If you want to learn how this works, I hugely recommend checking out Leetcode’s Sudoku Solver. It might be recommended to start of doing the Sudoku Validator, which is a simpler version of the solver. If you want a hint on how to solve the Leetcode problems, check the spoiler.

Use a HashSetSudoku Validator
Use a recursion algorithmSudoku Solver

Now after completing the sudoku solver, you may come to the same realization as I did. Which is that for a computer to solve the sudoku, the fastest way to do so is by guessing each number and backtracking if it cannot be solved with the current number. This is not how a human would solve a sudoku, and therefore we need to create a solver that can solve a sudoku that can be solved without guessing. We can and will still use the solver we made for the Leetcode problem to create the initially solved sudoku.

Making a human sudoku solver

A human solves a sudoku in multiple different ways, there are numerous different techniques used by those who love sudoku. If you want to read more on them you can visit Andrew Stuart’s Sudoku Solver. The most common techniques, and the ones I focused on using for my sudoku solver are:


Loading...