Created
November 24, 2014 23:04
-
-
Save wejn/b43a143ba85af8e03721 to your computer and use it in GitHub Desktop.
Cracking the Code Interview, Exercise 1.5
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
#!/usr/bin/env ruby | |
module Ex0105 | |
def self.compress(str) | |
out = str.scan(/./).reduce([[], 't', 0]) do |(buf, cur, num), c| | |
if cur == c | |
[buf, cur, num + 1] | |
else | |
if num > 0 | |
buf << cur | |
buf << num.to_s | |
end | |
[buf, c, 1] | |
end | |
end.join | |
if out.size < str.size | |
out | |
else | |
str | |
end | |
end | |
end | |
if __FILE__ == $0 | |
for test in %w[a aaa aaaaaaaaaaac abc aabcccccaa] + [""] | |
puts "compress('#{test}'): '#{Ex0105.compress(test)}'" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment