Skip to content

Instantly share code, notes, and snippets.

@AlexeyMK
Last active August 29, 2015 14:08
Show Gist options
  • Save AlexeyMK/d5f7a2df5c2d04f7f7e0 to your computer and use it in GitHub Desktop.
Save AlexeyMK/d5f7a2df5c2d04f7f7e0 to your computer and use it in GitHub Desktop.
module Enumerable
def bag
# [1,1,1,1,2,2,3] => {1 => 4, 2 => 2, 3 => 1}
# similar to python's Counter
Hash[group_by { |x| x }.map {|k, v| [k, v.count] }]
end
end
def print(grid)
system('clear')
min_x, max_x = grid.keys.map(&:first).minmax
min_y, max_y = grid.keys.map(&:last).minmax
result = min_y.upto(max_y).map do |y|
min_x.upto(max_x).map do |x|
grid[[x,y]] ? 'X' : ' '
end.to_a.join("")
end.to_a.join("\n")
puts result
end
def neighbors_of(location)
x_range = (location.first-1).upto(location.first+1).to_a
y_range = (location.last-1).upto(location.last+1).to_a
x_range.product(y_range) - [location]
end
def will_be_alive(was_alive, neighbors_count)
if was_alive
[2,3].include? neighbors_count
else
neighbors_count == 3
end
end
def iterate(old_grid)
old_grid.flat_map do |loc, _|
neighbors_of(loc)
end.bag.select do |loc, alive_near_me|
will_be_alive(old_grid[loc], alive_near_me)
end
end
def new_grid()
glider = [[1,0], [1, 2], [0,2], [2,2], [2,1]]
box = [[-3,3], [-3,4], [-4,3], [-4,4]]
alive_start = glider + box
Hash[alive_start.map { |k| [k, true] }]
end
grid = new_grid()
until grid.empty? do
print(grid)
grid = iterate(grid)
sleep 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment