Look and say sequence (Ruby)

From LiteratePrograms

Jump to: navigation, search
Other implementations: C++ | dc | Eiffel | Haskell | J | Java | Lua | OCaml | Perl | PHP | Python | Ruby | Scala | sed | sh

This program is a code dump.
Code dumps are articles with little or no documentation or rearrangement of code. Please help to turn it into a literate program. Also make sure that the source of this code does consent to release it under the MIT or public domain license.

This is a simple Ruby program to generate look-and-say sequences such as the Conway sequence.

<<look_and_say_sequence.rb>>=
require "generator"
def look_and_say(seed, len)
  Generator.new do |g|
    last_value = seed.to_s
    g.yield last_value
    2.upto(len) do
      next_value = ""
      while last_value.length > 0
        match = /#{last_value[0,1]}+/.match(last_value)[0]
        next_value << match.length.to_s + last_value[0,1]
        last_value = last_value[match.length..last_value.length]       
      end
      last_value = next_value
      g.yield next_value
    end 
  end
end

print conway sequence

We test the look and say sequence generator by printing the first 10 numbers of the Conway sequence to the console:

<<print conway sequence>>=
def test_look_and_say()
  conway = look_and_say(3,10)
  puts conway.to_a
end
Download code
Views