Skip to content

Instantly share code, notes, and snippets.

@wejn
Created November 24, 2014 23:04
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save wejn/b43a143ba85af8e03721 to your computer and use it in GitHub Desktop.
Cracking the Code Interview, Exercise 1.5
#!/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