Skip to content

Instantly share code, notes, and snippets.

@cfc1020
Last active March 22, 2021 12:24
Show Gist options
  • Save cfc1020/5f75bd89cfbf2f81f6bc to your computer and use it in GitHub Desktop.
Save cfc1020/5f75bd89cfbf2f81f6bc to your computer and use it in GitHub Desktop.
ruby look and say sequence 1 11 21 1211
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 "================================"
@cfc1020
Copy link
Author

cfc1020 commented Jan 2, 2015

1
11
21
1211
111221
312211
13112221
1113213211
31131211131221
13211311123113112211
11131221133112132113212221
================================
look_and_say_chunk
1
11
21
1211
111221
312211
13112221
1113213211
31131211131221
13211311123113112211
11131221133112132113212221
================================
look_and_say_manual
1
11
21
1211
111221
312211
13112221
1113213211
31131211131221
13211311123113112211
11131221133112132113212221
================================
[Finished in 0.2s]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment