Skip to content

Instantly share code, notes, and snippets.

@rosenfeld
Created May 2, 2012 20:49
Show Gist options
  • Save rosenfeld/2580380 to your computer and use it in GitHub Desktop.
Save rosenfeld/2580380 to your computer and use it in GitHub Desktop.
Conway's Game of Life in Ruby
class Life
attr_reader :live_cells
def initialize(live_cells)
@live_cells = live_cells
end
alias :to_a :live_cells
def next_generation
next_cells = alive_neighbors.each_with_object([]) do |(cell, neighbors_count), next_cells|
alive = @live_cells.include? cell
next_cells << cell if Life.alive_next?(neighbors_count, alive)
end
Life.new next_cells
end
def alive_neighbors
@live_cells.each_with_object(Hash.new(0)) do |(x, y), neighbors|
neighbor_cells = Array(x-1..x+1).product(Array(y-1..y+1)) - [[x, y]]
neighbor_cells.each {|cell| neighbors[cell] += 1 }
end
end
def self.alive_next?(neighbors_count, alive=true)
neighbors_count == 3 or alive && neighbors_count == 2
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment