Ruby String Encode Consecutive Letter Frequency -
i want encode string in ruby such output should in pairs decode it. want encode in such way each pair contains next distinct letter in string, , number consecutive repeats.
e.g if encode "aaabbcbbaaa" output should [["a", 3], ["b", 2], ["c", 1], ["b", 2], ["a", 3]]
here 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
"aaabbcbbaaa".scan(/((.)\2*)/).map{|s, c| [c, s.length]}
Comments
Post a Comment