Killer Sudoku is a popular variant on the perennial Sudoku game found in British newspapers. The same rules about the numbers 1 to 9 appearing only once in row, column and 3×3 box still apply, but unlike Sudoku, the puzzle doesn’t come with any numbers filled in. Instead, cells are groups with dotted lines and the total of all those cells are written in.
Here’s part of a puzzle. The two cells grouped by a 10 could be 1+9, 2+8, 3+7 or 4+6. (It can’t be 5+5 because that would mean two 5s in same box.) Not a lot to work on, but also look at the three cells grouped by a 23 in the same 3×3 box; The only possible fit is 6+8+9. This means the only possible fit for the 10 group is 3+7, as all the possibilities would clash with the 6,8 or 9 required to make the 23.
I could go on. If you want to complete the puzzle, its the Guardian‘s puzzle number 166. The point of this article isn’t to solve the puzzle, but something I observed along the way.
Am I sure there’s no other way to split 23 into three parts, 1 to 9, without duplicates? I confess, mental arithmetic is not my forte. Part of the puzzle solving process for me is going through each dotted group and building a crib sheet on all the possible ways to make the total, so I can cross them off later.
This isn’t a part of the puzzle I particularly enjoy, so I decided to automate it. (Is that cheating? I don’t think so in my circumstances, but that’s another topic of conversation.)
So I sat down and designed an algorithm…
- Input: n (the number of cells, 2 to 9) and m (the total, 3 to 45).
- Output: All solutions to SUM(n integers 1-9 without duplicates) = m.
Only problem, as with so many mathematical endeavors, life got in the way. By the time I had worked out a basic algorithm, I noticed it was 2AM and suddenly felt rather tired, but I didn’t want to stop, so I simplified my plan.
Loop, starting with (1,1,1,1,1,1) then (1,1,1,1,1,2), ending with (9,9,9,9,9,9). For each combination, if they add up to the target, have no duplicates, and is in order, add it to the list. It was a very inefficient algorithm, but it would work and I wouldn’t have to expend much thought on building it.
Then something surprising happened. While testing with 2 or 3 digit targets, it was near instantly fast, but I had expected 6 digit targets to take something like a few minutes. In fact, it took 2 seconds.
2 seconds!!!!! I had learnt to write programs on my early 80s BBC Micro and I was used to leaving it running overnight calculating something like this. Computers are fast!
(If all that seems too much like hard work. Wikipedia have built the tables for you.)