Created
May 22, 2020 02:23
-
-
Save richievos/81c4a2db94f44e52042c245cb14fef33 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
##################################### | |
# Main implementation | |
##################################### | |
def compress(string) | |
return "" if string.empty? | |
result = "" | |
cur_char = nil | |
count = 0 | |
string.chars.each do |char| | |
cur_char ||= char | |
if cur_char == char | |
count += 1 | |
else | |
result << "#{count}#{cur_char}" | |
cur_char = char | |
count = 1 | |
end | |
end | |
result << "#{count}#{cur_char}" | |
end | |
##################################### | |
# Helpers | |
##################################### | |
def verify(expected, base) | |
result = compress(base) | |
puts "pass=#{expected == result}, expected=#{expected}, result=#{result}, base=#{base}" | |
end | |
##################################### | |
# Tests | |
##################################### | |
verify("4a", "aaaa") | |
verify("", "") | |
verify("4a1b2c", "aaaabcc") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment