Last active
August 29, 2015 14:10
-
-
Save alpardal/2b68f080dad4d19623c2 to your computer and use it in GitHub Desktop.
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
def compress(string) | |
compressed = string.chars.inject([]) do |accu, char| | |
if accu.empty? || accu.last.first != char | |
accu << [char, 1] | |
else | |
accu[0...-1] << [char, accu.last.last + 1] | |
end | |
end.map(&:join).join | |
[string, compressed].min_by(&:length) | |
end | |
if __FILE__ == $0 | |
for test in %w[a aaa aaaaaaaaaaac abc aabcccccaa] + [""] | |
puts "compress('#{test}'): '#{compress(test)}'" | |
end | |
end | |
# >> compress('a'): 'a' | |
# >> compress('aaa'): 'a3' | |
# >> compress('aaaaaaaaaaac'): 'a11c1' | |
# >> compress('abc'): 'abc' | |
# >> compress('aabcccccaa'): 'a2b1c5a2' | |
# >> compress(''): '' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment