1+ # Problem: https://exercism.org/tracks/ruby/exercises/run-length-encoding
2+ 3+ # Solution (Brute force)
4+ class RunLengthEncoding
5+ def self . encode ( input )
6+ return "" if input ==""
7+ encoded_msg = ""
8+ curr_char_count = 0
9+ prev_char = ""
10+ input . chars . each do |char |
11+ if prev_char != char
12+ encoded_msg +="#{ curr_char_count >1 ?curr_char_count :"" } #{ prev_char } "
13+ prev_char = char
14+ curr_char_count = 0
15+ end
16+ curr_char_count +=1
17+ end
18+ encoded_msg +="#{ curr_char_count >1 ?curr_char_count :"" } #{ prev_char } "
19+ encoded_msg
20+ end
21+ 22+ def self . decode ( encoded_input )
23+ decoded_msg = ""
24+ curr_num_str = ""
25+ curr_char = ""
26+ encoded_input . chars . each do |char |
27+ if char . match ( /\d / )
28+ curr_num_str +=char
29+ next
30+ end
31+ decoded_msg +="#{ curr_num_str =="" ? char : ( char *curr_num_str . to_i ) } "
32+ curr_num_str = ""
33+ end
34+ decoded_msg
35+ end
36+ end
37+ 38+ # Solution(Using Regex)
39+ class RunLengthEncoding
40+ def self . encode ( input )
41+ input . gsub ( /(.)1円 +/ ) { |m | "#{ m . length } #{ m [ 0 ] } " }
42+ end
43+ 44+ def self . decode ( input )
45+ input . gsub ( /\d +./ ) { |m | m [ -1 ] * m . to_i }
46+ end
47+ end
48+ 49+ # Solution(Using Collections)
50+ class RunLengthEncoding
51+ def self . encode ( input )
52+ input
53+ . chars
54+ . chunk { |c | c }
55+ . collect { |k , v | [ v . length > 1 ? v . length : '' , k ] . join }
56+ . join
57+ end
58+ 59+ def self . decode ( input )
60+ input
61+ . scan ( /(\d *)([ \w ]+?)/ )
62+ . map { |c | c [ 1 ] * ( c [ 0 ] != '' ? c [ 0 ] . to_i : 1 ) }
63+ . join
64+ end
65+ end
0 commit comments