Module: NLife::Helper
- Defined in:
- lib/nlife/helper.rb
Overview
miscellaneous functions for state/surround gereration
Class Method Summary collapse
- .golly_to_array(string) ⇒ Object
-
.rule_from_arrays(birth, survival) ⇒ Object
constructs rules from two arrays: birth, survival densities.
-
.rule_from_golly(string) ⇒ Object
constructs rules from string, describing birth/survival densities.
-
.surround_from_block(rows, cols) ⇒ Object
surround is calculated for rectangle centered at (0, 0).
Class Method Details
.golly_to_array(string) ⇒ Object
33 34 35 36 37 38 39 40 |
# File 'lib/nlife/helper.rb', line 33 def golly_to_array(string) match = %r{^B([0-8]*)\/S([0-8]*)$}.match(string) raise ArgumentError 'wrong input format' unless match birth = (0..8).map { |i| match[1].include? i.to_s } survival = Array.new(9, false) match[2].split(//).map(&:to_i).each { |i| survival[i] = true } return birth, survival end |
.rule_from_arrays(birth, survival) ⇒ Object
constructs rules from two arrays: birth, survival densities
21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/nlife/helper.rb', line 21 def rule_from_arrays(birth, survival) unless birth.size == survival.size fail ArgumentError 'params sizes not match' end max_density = birth.size proc do |state, density| fail ArgumentError 'density too high' if density > max_density result = (state == 0 ? birth : survival)[density.round] result ? 1.0 : 0.0 end end |
.rule_from_golly(string) ⇒ Object
constructs rules from string, describing birth/survival densities
43 44 45 |
# File 'lib/nlife/helper.rb', line 43 def rule_from_golly(string) rule_from_arrays(*golly_to_array(string)) end |
.surround_from_block(rows, cols) ⇒ Object
surround is calculated for rectangle centered at (0, 0)
9 10 11 12 13 14 15 16 17 18 |
# File 'lib/nlife/helper.rb', line 9 def surround_from_block(rows, cols) result = NArray.float(cols, rows) result.shape[1].times do |row| result.shape[0].times do |col| result[col, row] = yield((row + rows / 2) % rows - rows / 2, (col + cols / 2) % cols - cols / 2) end end result end |