Created
February 27, 2011 02:38
-
-
Save paul/845858 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
OFFSETS = [ | |
[-1,-1], | |
[-1, 0], | |
[-1, 1], | |
[ 0,-1], | |
[ 0, 1], | |
[ 1,-1], | |
[ 1, 0], | |
[ 1, 1] | |
] | |
def neighbors(pos) | |
OFFSETS.map { |x,y, z| [pos[0]+ x, pos[1] + y } | |
end | |
def count_neighbors(positions = []) | |
Hash.new{|h,k| h[k] = 0}.tap do |counts| | |
positions.each do |pos| | |
neighbors(pos).each { |neighbor_pos| counts[neighbor_pos] += 1 } | |
end | |
end | |
end | |
def next_turn(positions = []) | |
counts = count_neighbors(positions) | |
[].tap do |new_positions| | |
counts.each do |pos, count| | |
new_positions << pos if count == 3 | |
new_positions << pos if count == 2 and positions.include?(pos) | |
end | |
end | |
end | |
require 'test/unit' | |
class LifeTest < Test::Unit::TestCase | |
def test_list_neighbor_positions | |
pos = [0,0] | |
neighbor_pos = neighbors(pos) | |
[ | |
[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1] | |
].each do |pos| | |
assert neighbor_pos.include?(pos) | |
end | |
end | |
def test_counting_neighbors | |
count = count_neighbors([[0,0]]) | |
assert count[ [1,1] ] == 1 | |
end | |
def testing_multiple_neighbors | |
count = count_neighbors([[0,0], [2,0]]) | |
assert count[ [1,0] ] == 2 | |
end | |
def test_next_turn_kills_cell | |
new = next_turn [[0,0]] | |
assert new.empty? | |
end | |
def test_stable_block | |
block = [ [0,0], [1,0], [0,1], [1,1] ] | |
new = next_turn block | |
block.each do |pos| | |
assert new.include?(pos) | |
end | |
end | |
def test_blinker | |
horz_bar = [ [-1,0], [0,0], [1,0] ] | |
new = next_turn horz_bar | |
vert_bar = [ [0,-1], [0,0], [0,1] ] | |
vert_bar.each do |pos| | |
assert new.include?(pos) | |
end | |
end | |
def test_blinker_after_two_turns | |
horz_bar = [ [-1,0], [0,0], [1,0] ] | |
new = next_turn(next_turn(horz_bar)) | |
horz_bar.each do |pos| | |
assert new.include?(pos) | |
end | |
end | |
def test_distant_blinkers | |
vert_bar = [ [0,-1], [0,0], [0,1] ] | |
vert_bar2 = [ [2,-1], [2,0], [2,1] ] | |
bars = vert_bar + vert_bar2 | |
new = next_turn bars | |
[[-1,0], [0,0], [2,0], [3,0]].each do |pos| | |
assert new.include?(pos) | |
end | |
next_new = next_turn new | |
assert next_new.empty? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment