Skip to content

Instantly share code, notes, and snippets.

@bhauman
Created July 20, 2013 18:08
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 bhauman/6045933 to your computer and use it in GitHub Desktop.
Save bhauman/6045933 to your computer and use it in GitHub Desktop.
def assert(phrase, val)
puts (val && "p #{phrase}" || "FAIL #{phrase}")
end
@offsets = [[0,1], [1,0], [-1,1], [1,-1], [-1, 0], [0, -1], [1,1], [-1,-1]]
world = {}
def neighbors_coordinates(coord)
x,y = coord
@offsets.map { |off|
ox,oy = off
[x + ox, y + oy]
}
end
def live_neighbors(coord, world)
neighbors_coordinates(coord).inject(0) { |count, currentCoord|
count += 1 if world.has_key?(currentCoord); count
}
end
def next_alive_val(coord, world)
live_count = live_neighbors(coord, world)
((live_count == 2 || live_count == 3)) && 1 || nil
end
def next_dead_val(coord, world)
live_count = live_neighbors(coord, world)
(live_count == 3 && 1) || nil
end
def next_val(coord, world)
world.has_key?(coord) && next_alive_val(coord, world) || next_dead_val(coord, world)
end
assert("offsets have right length", @offsets.length == 8)
assert("neighbors_coordinates([0,0]) should == @offsets", neighbors_coordinates([0,0]) == @offsets)
assert("neighbors_coordinates([5,5]) should be correct", neighbors_coordinates([5,5])[3] == [6,4])
world = {
[3,4] => 1,
[5,4] => 1,
[4,5] => 1,
[5,5] => 1,
[6,5] => 1,
[0,0] => 1
}
assert("live_neighbors([5,6], world) == 3", live_neighbors([5,6], world))
assert("next_val([5,6], world) == 1", next_val([5, 6], world) == 1);
assert("next_val([6,4], world) == 1", next_val([6,4], world) == 1);
assert("next_val([0,0], world) == nil", next_val([0,0], world) == nil);
world1 = {
[3,4] => 1,
[5,4] => 1,
[4,5] => 1
}
result_world = {
[4,4] => 1
}
def do_coord(c, world)
newVal = next_val(coord, world)
newVal if newVal
end
def next_world(world)
puts world.inspect
world.keys.inject({ }){ |new_world, coord|
puts coord.inspect + "__ " + next_val(coord, world).inspect
newVal = next_val(coord, world)
new_world[coord] = newVal if newVal
neighbors_coordinates(coord).each do |c|
puts c.inspect + "__ " + next_val(c, world).inspect
newVal = next_val(c, world)
new_world[c] = newVal if newVal
end
new_world
}
end
puts "______"
next_world(world1).inspect
assert("next_world(world1) == right world", next_world(world1) == result_world )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment