Haris Ali
Haris Ali

Reputation: 95

Ruby String Encode Consecutive Letter Frequency

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

Answers (4)

Arup Rakshit
Arup Rakshit

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

Dan Tao
Dan Tao

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

sawa
sawa

Reputation: 168121

"aaabbcbbaaa".scan(/((.)\2*)/).map{|s, c| [c, s.length]}

Upvotes: 5

DigitalRoss
DigitalRoss

Reputation: 146093

'aaabbcbbaaa'.scan(/((.)\2*)/).map {|e| [e[1], e[0].size]}

Upvotes: 1

Related Questions