Created
March 1, 2014 18:39
-
-
Save st98/9294858 to your computer and use it in GitHub Desktop.
Rubyの練習。一次元セルオートマトン。
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
class String | |
def zfill(width) | |
self.rjust(width, '0') | |
end | |
end | |
class ElementaryCellularAutomaton | |
attr_reader :rule, :width, :cells | |
def initialize(rule = rand(256), width = 75) | |
@rule = rule | |
@width = width | |
end | |
def rule=(rule) | |
@rule = rule.to_s(2).zfill(8).reverse.split('').map(&:to_i) | |
end | |
def width=(width) | |
@width = width.to_i | |
end | |
def cells=(cells) | |
@cells = cells.to_a | |
end | |
def init | |
@cells = [].fill(0, 0 ... @width) | |
@cells[@cells.size / 2] = 1 | |
end | |
def update | |
new_cells = [] | |
for x in 0 ... @cells.size | |
new_cells.push(@rule[ | |
(@cells[x - 1] << 2) | (@cells[x] << 1) | @cells[(x + 1) % @cells.size] | |
]) | |
end | |
@cells = new_cells | |
end | |
def to_s | |
@cells.map do |cell| | |
cell == 1 ? '#' : ' ' | |
end.join('') | |
end | |
end | |
if __FILE__ == $0 | |
eca = ElementaryCellularAutomaton.new(90) | |
eca.init | |
32.times do | |
puts eca.to_s | |
eca.update | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment