Reputation: 95
I want to encode a string in Ruby such that output should be in pairs so that I could decode it. I want to encode in such a way that each pair contains the next distinct letter in the string, and the number consecutive repeats.
e.g If I encode "aaabbcbbaaa" output should [["a", 3], ["b", 2], ["c", 1], ["b", 2], ["a", 3]]
here is the code.
def encode( s )
b = 0
e = s.length - 1
ret = []
while ( s <= e )
m = s.match( /(\w)\1*/ )
l = m[0][0]
n = m[0].length
ret << [l, n]
end
ret
end
Upvotes: 3
Views: 894
Reputation: 118271
"aaabbcbbaaa".chars.chunk{|i| i}.map{|m,n| [m,n.count(m)]}
#=> [["a", 3], ["b", 2], ["c", 1], ["b", 2], ["a", 3]]
Upvotes: 8
Reputation: 128327
You could also do this procedurally.
def group_consecutive(input)
groups = []
input.each_char do |c|
if groups.empty? || groups.last[0] != c
groups << [c, 1]
else
groups.last[1] += 1
end
end
groups
end
Upvotes: 4