Class: Automata::Elementary
- Inherits:
-
Object
- Object
- Automata::Elementary
- Defined in:
- lib/automata/elementary.rb
Instance Attribute Summary collapse
-
#rule ⇒ Object
readonly
Returns the value of attribute rule.
-
#state ⇒ Object
readonly
Returns the value of attribute state.
-
#steps ⇒ Object
readonly
Returns the value of attribute steps.
Class Method Summary collapse
- .step(state, trans) ⇒ Object
-
.transformer(rule_num) ⇒ Object
This elegantly simple algorithm and code is from Jesse Merriman written for Ruby Quiz 134: Cellular Automata.
Instance Method Summary collapse
-
#initialize(rule, state = ['1']) ⇒ Elementary
constructor
A new instance of Elementary.
- #run(steps) ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize(rule, state = ['1']) ⇒ Elementary
Returns a new instance of Elementary.
22 23 24 |
# File 'lib/automata/elementary.rb', line 22 def initialize(rule, state = ['1']) @rule, @state = rule, state end |
Instance Attribute Details
#rule ⇒ Object (readonly)
Returns the value of attribute rule.
21 22 23 |
# File 'lib/automata/elementary.rb', line 21 def rule @rule end |
#state ⇒ Object (readonly)
Returns the value of attribute state.
21 22 23 |
# File 'lib/automata/elementary.rb', line 21 def state @state end |
#steps ⇒ Object (readonly)
Returns the value of attribute steps.
21 22 23 |
# File 'lib/automata/elementary.rb', line 21 def steps @steps end |
Class Method Details
.step(state, trans) ⇒ Object
13 14 15 16 17 18 19 |
# File 'lib/automata/elementary.rb', line 13 def self.step(state, trans) new_state = [] ([0,0] + state + [0,0]).each_cons(3) do |hood| new_state << trans[hood] end new_state end |
.transformer(rule_num) ⇒ Object
This elegantly simple algorithm and code is from Jesse Merriman written for
Ruby Quiz 134: Cellular Automata. see: http://www.rubyquiz.com/quiz134.html
7 8 9 10 11 |
# File 'lib/automata/elementary.rb', line 7 def self.transformer(rule_num) rule = rule_num.to_s 2 rule = ('0' * (2**3 - rule.length) + rule).reverse.split(//) lambda { |hood| rule[hood.join.to_i(2)] } end |
Instance Method Details
#run(steps) ⇒ Object
26 27 28 29 30 31 32 |
# File 'lib/automata/elementary.rb', line 26 def run(steps) trans = Elementary.transformer(@rule) steps.times do |s| @state = Elementary.step(@state, trans) end self end |
#to_s ⇒ Object
34 35 36 |
# File 'lib/automata/elementary.rb', line 34 def to_s @state.join('') end |