Class: Automata::Elementary

Inherits:
Object
  • Object
show all
Defined in:
lib/automata/elementary.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

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

#ruleObject (readonly)

Returns the value of attribute rule.



21
22
23
# File 'lib/automata/elementary.rb', line 21

def rule
  @rule
end

#stateObject (readonly)

Returns the value of attribute state.



21
22
23
# File 'lib/automata/elementary.rb', line 21

def state
  @state
end

#stepsObject (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_sObject



34
35
36
# File 'lib/automata/elementary.rb', line 34

def to_s
  @state.join('')
end