Skip to content

Instantly share code, notes, and snippets.

@saturnflyer
Last active December 21, 2015 00:09
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 saturnflyer/6217683 to your computer and use it in GitHub Desktop.
Save saturnflyer/6217683 to your computer and use it in GitHub Desktop.
Conway's Game of Life
seed = [[0,0],[0,1],[0,2]]
puts "First generation:"
puts seed.to_s
# Point surrounding a given point
perimeter = ->(x, y){
[
[x - 1, y + 1], [x, y + 1], [x + 1, y + 1],
[x - 1, y ], [x + 1, y ],
[x - 1, y - 1], [x, y - 1], [x + 1, y - 1]
]
}
# All points and their perimeters
world = ->(seed){
seed.inject([]) do |array, point|
array.concat(perimeter.(*point))
end.concat(seed).uniq
}
# For a dead point and a living perimeter, get the next state
dead_next_point = ->(point, living){
if living.size == 3
point
end
}
# For a point and living seed, get the living points in the perimeter
living_perimeter = ->(point, seed){
seed & perimeter.(*point)
}
# For a point and living perimeter, get the next state
living_next_point = ->(point, living){
case living.size
when 0, 1 then nil
when 2, 3 then point
else
nil
end
}
# For a point and living seed, get the next state
next_point = ->(point, seed){
if seed.include?(point)
living_next_point.(point, living_perimeter.(point, seed))
else
dead_next_point.(point, living_perimeter.(point, seed))
end
}
# Gather each points' next state
generate = ->(seed){
world.(seed).map do |point|
next_point.(point, seed)
end.compact
}
puts "More generations"
9.times do |num|
seed = generate.(seed)
puts seed.to_s
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment