Elementary Cellular Automaton

While looking for information on the Celluloid projecthttp://celluloid.io/, I came across this blog posthttp://grahamedgecombe.com/blog/elementary-ce… (you can see the mistake, I’m blaming Google’s annoyingly overzealous spelling correction:)

I’d not heard of elementary cellular automatahttps://en.wikipedia.org/wiki/Elementary_cell… before, and though Graham’s code was fine, it’s not what I would call Rubyish (bitwise operations and array indices aren’t the first port of call unless you’ve written a fair amount of C or Java…) After reading a bithttp://mathworld.wolfram.com/ElementaryCellul… I decided to write something that used object orientation and blocks, and replaced all those binary digits with real words. I could’ve taken it further, perhaps allow the Renderer module’s methods to take a block; maybe added a convenience method for the rendering, but I’m happy with the result. It means you can do something like this:

# rule 111, 30 cells wide
first_gen = Generation.new 111, 30 do
  Cell.new # random cells in first generation

# evolve from the first generation 60 times
generations = Generation.evolve_generations first_gen, 60

# render them to the terminal
generations.each do |gen|
  gen.each do |cell|
    cell.render black: "*"
  print "\n"

That looks a lot more like Ruby to me. YMMV.

I also added in some documentation using Yardochttp://yardoc.org/ which makes it incredibly easy to produce API documentation from the comments. I suggest you try it out. Perhaps download the code and install the gem and run bin/yard -o doc 'Elementary cellular automaton.rb' and open up the index.html file in the doc directory.

Added on:
Last updated:
  • Ruby v1.9.3
  • Tags