Last active
September 27, 2021 15:04
-
-
Save AlexAvlonitis/a7b20332605fd16f7b9ed2bab2e53d31 to your computer and use it in GitHub Desktop.
String compression method in ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://github.com/alexavlonitis | |
# Simple string compression 'aaabbb' to 'a3b3' | |
def compress_string(text) | |
consecutive_chars = text.each_char.chunk_while(&:==).map(&:join) | |
consecutive_chars.map do |chars| | |
chars_group = chars.split('') | |
chars_group.first + chars_group.length.to_s | |
end.join | |
end | |
## Convoluted manual way | |
def compress_string(text) | |
result_array = [] | |
split_text = text.split('') | |
counter = 1 | |
split_text.each.with_index(1) do |char, lookahead_index| | |
result_array << char if counter == 1 | |
counter += 1 if result_array.last == split_text[lookahead_index] | |
if result_array.last != split_text[lookahead_index] && counter != 1 | |
result_array << counter | |
counter = 1 | |
end | |
end | |
result_array.join | |
end | |
## decompress string | |
def decompress_string(text) | |
# subarray after every digit | |
grouped_array_text = text.each_char.chunk_while { |i, j| j =~ /\A[0-9]\z/ }.to_a | |
# if the subarray has a number (size > 1) then get the first value (letter) | |
# and multiply the combined digits of the remainder | |
grouped_array_text.map { |x| x.size > 1 ? x.shift * x.join.to_i : x.first }.join | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment