# \[SOLUTION\] Cellular Automata (#134)

**URL:** <https://www.ruby-forum.com/t/solution-cellular-automata-134/112092>\
**Category:** Ruby\
**Created:** [August 15, 2007, 8:41am UTC](https://www.ruby-forum.com/t/solution-cellular-automata-134/112092 "2007-08-15T08:41:42Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![jameskelly](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/3ab097/32.png) [@jameskelly](https://www.ruby-forum.com/u/jameskelly)\
**Post date:** [August 15, 2007, 8:41am UTC](https://www.ruby-forum.com/t/solution-cellular-automata-134/112092/1 "2007-08-15T08:41:42Z")

</div>

Here’s my simple solution. Note that, rather than parsing options, it  
merely expects rule, steps, state in that order.

require ‘enumerator’

def step(state,rule)  
cur\_arr = ([0,0] + state.split(//) + [0,0]).map{|s| s.to\_i}  
next\_arr = []  
cur\_arr.each\_cons(3) do |neighborhood|  
##Checks the (neighborhood+1)th bit of rule  
##E.g.: If neighborhood is [0,1,0], then inserts a 1 if the third  
bit of rule is on  
if (2\*\*(neighborhood.join.to\_i(2)))&rule != 0  
next\_arr \<\< 1  
else  
next\_arr \<\< 0  
end  
end  
next\_arr.join  
end

rule = ARGV[0].chomp.to\_i  
steps = ARGV[1].chomp.to\_i  
state = ARGV[2].chomp

result = [state]

steps.times do  
state = step(state, rule)  
result \<\< state  
end

length = result.last.size

output = result.map {|row|  
([0]\*((length-row.size)/2)+row.split(//)).map{|b|  
b==“1” ? “X” : " "}.join  
}

puts output
