Skip to content

Instantly share code, notes, and snippets.

@thomasfedb
Created May 10, 2010 14:43
Show Gist options
  • Save thomasfedb/396111 to your computer and use it in GitHub Desktop.
Save thomasfedb/396111 to your computer and use it in GitHub Desktop.
class Array
define_method "/" do |len|
a = []
each_with_index do |x,i|
a << [] if i % len == 0
a.last << x
end
a
end
def count(item)
count = 0
each do |x|
if x == item
count += 1
end
end
count
end
end
class Position
def initialize(id)
@id = id
end
def id
@id
end
def x
@id % 9
end
def y
(@id / 9).floor
end
end
class Cell
def initialize(id)
@possible = (1..9).to_a
@parents = []
@id = Position.new(id)
end
def cant_be(value)
@possible .delete value
end
def must_be(value)
@possible = [value]
end
def solved?
@possible.size == 1
end
def can_be
@possbile
end
def value
@possible.first if solved?
end
def parents
@parents
end
def each_parent
@parents.each do |parent|
yeild(parents)
end
end
def position
@position
end
def belongs_to(parent)
@parents << parent
end
def siblings
siblings = []
@parents.each do |parent|
siblings.concat(parent.children)
end
slibings.uniq!.delete self
end
def each_sibling
siblings.each do |sibling|
yeild(sibling)
end
end
end
class CellGroup
def initialize(children)
@children = members
@possible = (1..9).to_a
# Tell the children we are a parent
@children.each do |child|
child.belongs_to(self)
end
end
def children
@children
end
def each_child
@children.each do |child|
yeild(child)
end
end
end
class Puzzle
def initialize
@grid_numbers = (0..80).to_a
@cells = []
grid_numbers.each do |cell|
@cells[cell] = Cell.new(cell)
end
@groups = []
row_contents = grid_numbers / 9
column_contents = []
(0..8).to_a.each do |x|
column_contents[x] = []
row_contents.each do |row|
column_contents[x] << row[x]
end
end
box_contents = []
3.times do |x|
row_a = row_contents[x * 3] / 3
row_b = row_contents[x * 3 + 1] / 3
row_c = row_contents[x * 3 + 2] / 3
3.times do |y|
box_contents << row_a[y] + row_b[y] + row_c[y]
end
end
group_contents = box_contents + row_contents + column_contents
group_contents.each do |group|
children = []
group.each do |child_index|
children << @cells[child_index]
end
@groups << CellGroup.new(children)
end
end
def cell
@cells
end
def each_cell
@cells.each do |cell|
yeild(cell)
end
end
def groups
@groups
end
def each_group
@groups.each do |group|
yeild(group)
end
end
def get_cell(x, y)
@cells[x + 9 * y]
end
def set_cell(x, y, value)
@cells[x + 9 * y].must_be(value)
end
def solved?
grid_numbers.each do |cell|
if not @cells[cell].solved?
return false
end
end
true
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment