Skip to content

Instantly share code, notes, and snippets.

@gmarik
Created March 19, 2012 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gmarik/2119373 to your computer and use it in GitHub Desktop.
Save gmarik/2119373 to your computer and use it in GitHub Desktop.
Conway's Game of life
require 'set'
cells = lambda do |world, (x, y)|
[
[-1,-1], [0, -1], [1, -1],
[-1, 0], [1, 0],
[-1, 1], [0, 1], [1, 1],
].map do |(dx, dy)|
[x+dx, y+dy]
end.partition { |_cell| world.include?(_cell) }
end
advance = lambda do |world|
Set.new.tap do |_world|
world.each do |cell|
occupied, available = cells[world, cell]
_world << cell if (2..3).include?(occupied.size)
available.each do |cell|
occupied, _ = cells[world, cell]
_world << cell if occupied.size == 3
end
end
end
end
b = Set.new
b << [0,0]
b << [1,0]
b << [2,0]
b << [0,1]
b << [1,2]
100.times do
b = advance[b]
end
p b
# .
#...## ..###
#.#### .#.##
##.### #####
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment