On Mon, Nov 10, 2008 at 12:25 PM, Matthew Moss <matt / moss.name> wrote:
>> ## Sudoku Generator (#182)
>>
>> _Quiz idea provided by Lloyd Linklater_
>>
>> A bit over three years ago, we had a quiz to [solve sudoku puzzles][1].
>> Now it's time to write a script that generates sudoku puzzles.
>
> If the requirement to create puzzles of specified difficulty (or determine a
> puzzle's difficulty) is too much, feel free to simply generate a puzzle.

I haven't take the time to look at difficulty level, but have a very
naive generator; the basic idea is to generate a puzzle using a sudoku
solver and then punch some random holes in it:

#!/usr/bin/env ruby

# so far, only sudoku-x has completed in the time I'm willing to wait :-)
#require 'small_sudoku_solver'
#require 'yet_another_sudoku_solver'
require 'sudoku-x'

require 'enumerator'

puzzle = [0] * 81

a = (1..9).sort_by{rand}
b = (1..9).sort_by{rand}
c = (1..9).sort_by{rand}

puzzle[0..2] = a[0..2]
puzzle[9..11] = a[3..5]
puzzle[18..20] = a[6..8]

puzzle[30..32] = b[0..2]
puzzle[39..41] = b[3..5]
puzzle[48..50] = b[6..8]

puzzle[60..62] = b[0..2]
puzzle[69..71] = b[3..5]
puzzle[78..80] = b[6..8]

puts "Seed Puzzle"
puzzle.each_slice(9){|s| p s}
puts

puzzle = solve(puzzle)

puts "Solved Puzzle"
puzzle.each_slice(9){|s| p s}
puts

72.times{puzzle[rand(81)] = 0}

puts "Puzzle"
puzzle.each_slice(9){|s| p s}
puts

Full output:

Seed Puzzle
[6, 8, 5, 0, 0, 0, 0, 0, 0]
[3, 1, 9, 0, 0, 0, 0, 0, 0]
[7, 2, 4, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 2, 1, 8, 0, 0, 0]
[0, 0, 0, 4, 5, 6, 0, 0, 0]
[0, 0, 0, 9, 7, 3, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 2, 1, 8]
[0, 0, 0, 0, 0, 0, 4, 5, 6]
[0, 0, 0, 0, 0, 0, 9, 7, 3]

Solved Puzzle
[6, 8, 5, 7, 3, 9, 1, 2, 4]
[3, 1, 9, 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