run_length_encoding.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class RunLengthEncoding
  VERSION = 1

  def self.encode(input)
    groups = input.split('').chunk {|c| c}
    groups.map {|char, group|
      group.length == 1 ? char : "#{group.length}#{char}"
    }.join
  end

  def self.decode(input)
    input.scan(/\d*./).map {|run|
      run.length == 1 ? run[0] : (run[-1] * run.to_i)
    }.join
  end
end

Comments


You're not logged in right now. Please login via GitHub to comment