r/dailyprogrammer • u/Cosmologicon 2 3 • Nov 06 '12
[11/6/2012] Challenge #111 [Intermediate] The First Sudoku
Find the lexicographically first valid sudoku. A valid sudoku consists of a 9x9 grid of the numbers 1-9 such that no number appears twice in any row or column, or in any of the 9 major 3x3 sub-grids. Two sudokus can be compared to determine which is lexicographically first like this: append the rows for each of the two sudokus together. Find the first number where they differ. Whichever sudoku has a smaller number in that position is lexicographically first.
Here's the solution you should get:
[1, 2, 3, 4, 5, 6, 7, 8, 9][4, 5, 6, 7, 8, 9, 1, 2, 3][7, 8, 9, 1, 2, 3, 4, 5, 6][2, 1, 4, 3, 6, 5, 8, 9, 7][3, 6, 5, 8, 9, 7, 2, 1, 4][8, 9, 7, 2, 1, 4, 3, 6, 5][5, 3, 1, 6, 4, 2, 9, 7, 8][6, 4, 2, 9, 7, 8, 5, 3, 1][9, 7, 8, 5, 3, 1, 6, 4, 2]
If you want more of a challenge, find the lexicographically first valid 16x16 sudoku, or even larger.
Thanks to user Thomas1122 for suggesting this problem in /r/dailyprogrammer_ideas!
5
u/Ledrug 0 2 Nov 06 '12 edited Nov 07 '12
C (c99). Very much unreadable, but it's able to solve some rather larger boards. [edit] changed backtracking method; faster, even less readable
3
u/skeeto -9 8 Nov 06 '12
ANSI C. It's a generic Sudoku solver (9x9, 16x16, etc),
Give it an empty matrix and it will fill in the first lexicographically valid Sudoku.
Output for 16x16:
2
u/dreugeworst Nov 07 '12 edited Nov 08 '12
very ugly c++11 solution, using too many types :p At least it doesn't make a copy of the board with each change I guess.
slow as hell for every size above blocksize 4, with the exception of 9 it seems (which it finds instantaneously...) not sure how that happened.
2
u/dreugeworst Nov 09 '12
another solution, this time in python. From the performance characteristics it seems similar to Ledrug's solution, but I'm not sure cause I haven't taken the time to understand his code...
Basically, the problem for a sudoku with n2 blocks (so the entire board is n4) is reduced to finding the first latin square of size n2, and filling n rows of length n2 given a partially filled board.
I suspect that there should be a better way of generating the first valid latin square, but I couldn't find a correct algorithm.
[edit: fix typo]
1
u/ixid 0 0 Nov 06 '12 edited Nov 06 '12
In the D language, a general purpose solver given a blank board produces the first valid Sudoku. It uses bit-shifting to block possibilities until only 1 candidate remains or the square is unfillable in which case it backtracks:
DIM sets the dimensions of the Sudoku to be solved. The answer for a 16 by 16 Sudoku is:
1
u/LOOKITSADAM 0 0 Nov 13 '12 edited Nov 13 '12
Java:
product:
16x16
started on 25x25, let's see if it gets anywhere overnight