Last active
April 23, 2020 14:45
-
-
Save taiyoslime/4c4391c28733d8f1fafb66533a12dbef to your computer and use it in GitHub Desktop.
Elementary cellular automatonをシミュレートする
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 Eca | |
attr_reader :cells | |
def initialize(role, size = 200) | |
@role = role | |
@cells = Array.new(size, 0) | |
raise if role < 0 || role > 255 | |
end | |
def set(f, offset = nil) | |
str = f.is_a?(Integer) ? f.to_s(2) : f.is_a?(String) ? f : nil | |
raise if !str | |
@cells = Array.new(@cells.size, 0) | |
if offset | |
raise if offset + str.size > @cells.size | |
str.size.times{ |i| | |
@cells[offset + i] = str[i] | |
} | |
else | |
raise if str.size > @cells.size | |
str.size.times{ |i| | |
@cells[@cells.size / 2 - str.size / 2 + i] = str[i] | |
} | |
end | |
@cells | |
end | |
def step(n = 1) | |
n.times{ | |
new_cells = @cells.dup | |
@cells.size.times{|i| | |
c = @cells[i - 1, 3] * "" | |
c = "0" + c if i == 0 | |
c = c + "0" if i == @cells.size - 1 | |
new_cells[i] = @role[c.to_i(2)] | |
} | |
@cells = new_cells | |
} | |
@cells | |
end | |
def inspect | |
@cells * "" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment