For some reason, my sister’s stupid school gave her a homework to solve a peculiar sudoku puzzle for extra credits. it’s pretty annoying, and she just couldn’t figure it out, so I was now up for the task.
There is no way I’m gonna waste time solving a sudoku, but what I will do is sharpen those programming blades of mine… Anyways, enough about me, and more about the actual problem.
Sudoku Pie, Literally
You get my point now.
First, I have already written a stupid sudoku solver that uses backtracking, but it didn’t work at all. So, instead of wasting time on that idea, I decided to first try my luck!
Going over all the empty slots, calculate the possible entries for each slot, then simply fill the slots randomly till the puzzle is solved!
Pretty stupid and shitty code, but I had limited time, and I just wanted to run anything. I ran that code on all 8 cores, and it still didn’t yield a result after a few hours of crunching.. Seemed like not a feasible solution :(
I actually solved it on my second attempt, by just scratching my head a bit, and figuring out why this random generator was so bad.
It is really bad because once it picks a solution for a slot, it should update the other affected slots that this recently picked number is taken! That should cut down the iterations, I thought.
It was fairly simple to write this… First, by seeing the puzzle, all slots in the same color share a pool of possible numbers. It is the same for all slots. Then, the slots on the same ring share a pool themselves. For each slot, the possible numbers is the intersection of both.
With that in mind, just create these two pools, and for each slot, intersect the color pool with the ring pool that the slot is on, and now we have the reduced possible numbers!
Once you pick a number for the slot, remove it from both pools, and continue your loop. As simple as that.
The beauty here is that we don’t have to check the board each time, which further speeds up the process, since if we run out of possible values for a slot, that is a flag for us that we need to restart.
What really helped in this case, is that there is more than one solution! So, the random isn’t looking for a single answer among billions.
That solver is really fast, runs in under 500 ms, and the problem is solved!