Last active
March 22, 2021 12:24
-
-
Save cfc1020/5f75bd89cfbf2f81f6bc to your computer and use it in GitHub Desktop.
ruby look and say sequence 1 11 21 1211
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class String | |
def look_and_say_regexp | |
self.gsub(/(.)\1*/) { |match| "#{match.size}#{match[0]}" } | |
end | |
def look_and_say_chunk | |
self.chars.chunk { |c| c }.map { |c, arr| [arr.size, c] }.join | |
end | |
def look_and_say_manual | |
cluster = [] | |
self.each_char do |c| | |
if cluster.last && cluster.last.last == c | |
cluster.last << c | |
else | |
cluster << [c] | |
end | |
end | |
cluster.map { |e| [e.size, e.last] }.join | |
end | |
end | |
puts "look_and_say_regexp" | |
puts s = '1' | |
10.times { puts s = s.look_and_say_regexp } | |
puts "================================" | |
puts "look_and_say_chunk" | |
puts s = '1' | |
10.times { puts s = s.look_and_say_chunk } | |
puts "================================" | |
puts "look_and_say_manual" | |
puts s = '1' | |
10.times { puts s = s.look_and_say_manual } | |
puts "================================" | |
Author
cfc1020
commented
Jan 2, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment