Skip to content

Instantly share code, notes, and snippets.

@aarkerio
Last active November 7, 2018 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aarkerio/8ffe96e5754725c37fb835d701640063 to your computer and use it in GitHub Desktop.
Save aarkerio/8ffe96e5754725c37fb835d701640063 to your computer and use it in GitHub Desktop.
Encode & decode strings Ruby
class RunLengthEncoding
def self.encode(input)
new_array = split_by_chars input
ordered = new_array.map do |el|
el.length > 1 ? "#{el.length}#{el.chr}" : el
end.join
end
def self.decode(input)
tempo = split_by_numbers input
tempo.map.with_index(0) do |e, i|
if is_integer?(e)
tempo[i+1] * e.to_i
elsif num?(e) == false && num?(tempo[i-1]) == false
e
end
end.join
end
def self.split_by_chars(my_str)
my_str.scan(/((\w|\s)\2*)/).map(&:first)
end
def self.split_by_numbers(my_str)
my_str.each_char.slice_when{ |a,b| is_integer?(a) != is_integer?(b) || !is_integer?(a) && !is_integer?(b)}.map(&:join)
end
def self.num?(e)
numero = Integer(e) rescue false
numero.is_a?(Integer)
end
def self.is_integer?(str)
str.to_i.to_s == str
end
end
# TEST
def test_encode_with_repeated_characters
output = '12WB12W3B24WB'
input = 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB'
assert_equal output, RunLengthEncoding.encode(input)
end
def test_decode_with_repeated_characters
input = '12WB12W3B24WB'
output = 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB'
assert_equal output, RunLengthEncoding.decode(input)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment