Created
February 27, 2011 04:41
-
-
Save kevinolsen/845908 to your computer and use it in GitHub Desktop.
conway idea
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
require 'test/unit' | |
class Conway | |
def self.map_new_world(world) | |
interstitial_world = {} | |
world.each do |location| | |
(location[0]-1).upto(location[0]+1) do |x| | |
(location[1]-1).upto(location[1]+1) do |y| | |
interstitial_world[[x, y]] ||= {} | |
interstitial_world[[x, y]][:alive] = true and next if location[0] == x and location[1] == y | |
interstitial_world[[x, y]][:count] = interstitial_world[[x, y]][:count].to_i + 1 | |
end | |
end | |
end | |
interstitial_world | |
end | |
def self.reduce_new_world(interstitial_world) | |
next_world = [] | |
interstitial_world.each do |location, properties| | |
next_world << location if properties[:alive] && [2, 3].include?(properties[:count]) | |
next_world << location if !properties[:alive] && properties[:count] == 3 | |
end | |
next_world | |
end | |
def self.iterate(world) | |
reduce_new_world(map_new_world(world)) | |
end | |
end | |
class ConwayTest < Test::Unit::TestCase | |
def test_block | |
world = [] | |
world << [40, 40] | |
world << [40, 41] | |
world << [41, 40] | |
world << [41, 41] | |
assert_equal Conway.iterate(world), world | |
end | |
def test_boat | |
world = [] | |
world << [1, 1] | |
world << [1, 2] | |
world << [2, 1] | |
world << [2, 3] | |
world << [3, 2] | |
assert_equal Conway.iterate(world), world | |
end | |
def test_spinner | |
world = [] | |
world << [41, 40] | |
world << [41, 41] | |
world << [41, 42] | |
assert_equal Conway.iterate(world), [[40, 41], [41, 41], [42, 41]] | |
end | |
def test_glider | |
world = [] | |
world << [0, 1] | |
world << [1, 2] | |
world << [2, 0] | |
world << [2, 1] | |
world << [2, 2] | |
new_world = world | |
4.times { new_world = Conway.iterate(new_world) } | |
#after 4 cycles the glider should have moved 1,1 | |
assert_equal new_world - world.map { |x, y| [x+1, y+1] }, [] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In J, this can be done with:
lifenext =: 3 3 (neighbours e. 3,2 if alive) tesselate on coat
where
neighbours =: (+/,)-alive
on =: @.
alive =: (<1 1)&{
if =: #~
tesselate =: ;,_3
coat =: (0,) on (0,
) on (0,"1) on (0,"1)If one dispenses with the names, the whole expression is a single sentence. Now, that's elegant.