Skip to content

Instantly share code, notes, and snippets.

@richievos
Created May 22, 2020 02:23
Show Gist options
  • Save richievos/81c4a2db94f44e52042c245cb14fef33 to your computer and use it in GitHub Desktop.
Save richievos/81c4a2db94f44e52042c245cb14fef33 to your computer and use it in GitHub Desktop.
#####################################
# 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