Skip to content

Instantly share code, notes, and snippets.

@micahrj
Created September 15, 2012 03:22
Show Gist options
  • Save micahrj/3726235 to your computer and use it in GitHub Desktop.
Save micahrj/3726235 to your computer and use it in GitHub Desktop.
require 'set.rb'
class Cell
attr_reader :contents, :done
def initialize(grid, x, y, contents)
@grid = grid; @x = x; @y = y
if contents == 0
@contents = Set[1, 2, 3, 4, 5, 6, 7, 8, 9]
else
@contents = contents
@done = true
end
end
def propagate
if @done
(0..8).each do |n|
@grid[@y][n].eliminate(@contents) if n != @x
@grid[n][@x].eliminate(@contents) if n != @y
square_x = @x.div(3) * 3
square_y = @y.div(3) * 3
(square_y .. square_y + 2).each do |y|
(square_x .. square_x + 2).each do |x|
@grid[y][x].eliminate(@contents)
end
end
end
end
end
def eliminate(n)
if not @done
@contents.delete(n)
if @contents.size == 1
@contents = @contents.to_a[0]
@done = true
propagate
end
end
end
end
def solve(puzzle)
grid = []
puzzle.each_with_index do |row, y|
grid[y] = []
row.each_with_index do |cell, x|
grid[y][x] = Cell.new(grid, x, y, cell)
end
end
grid.each do |row|
row.each do |cell|
cell.propagate
end
end
grid.map { |row| row.map { |cell| if cell.done; cell.contents; else; 0; end } }
end
solve([[2, 0, 4, 0, 3, 0, 8, 0, 0],
[0, 0, 0, 0, 2, 7, 0, 0, 5],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[3, 0, 1, 5, 0, 0, 0, 0, 7],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[7, 0, 0, 0, 0, 3, 2, 0, 6],
[0, 0, 3, 0, 0, 0, 0, 0, 0],
[6, 0, 0, 4, 8, 0, 0, 0, 0],
[0, 0, 8, 0, 9, 0, 5, 0, 1]]).each { |row| puts row.to_s }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment