Last active
August 29, 2015 14:10
-
-
Save jah2488/9fe007f943b4b2558578 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
| def compress_before_seeing_avdis_answer(str) | |
| result = str.chars.chunk(&:to_s).map { |char, chars| "#{char}#{chars.length}" }.join | |
| return str if result.length > str.length | |
| result | |
| end | |
| def compress(str) | |
| [ | |
| str | |
| str.chars.chunk(&:to_s).map { |char, chars| "#{char}#{chars.length}" }.join, | |
| ].min_by(&:length) | |
| end | |
| def decompress(str) | |
| #double split and double empty seems like a huge smell. Something is a miss here. | |
| [ | |
| str.split(/([a-z][0-9]+)/) | |
| .reject(&:empty?) | |
| .map do |num| | |
| alpha_num = num.split(/([a-z]|[0-9]+)/).reject(&:empty?) | |
| alpha_num.first * alpha_num.last.to_i | |
| end.join, | |
| str | |
| ].max_by(&:length) | |
| end | |
| describe 'compress / decompress' do | |
| cases = [ | |
| ['a', 'a'], | |
| ['aa', 'aa'], | |
| ['aaa', 'a3'], | |
| ['abc', 'abc'], | |
| ['aaaaaaaaaaac', 'a11c1'], | |
| ['aabcccccaa', 'a2b1c5a2'], | |
| ] | |
| cases.each do |start, finish| | |
| it "compresses #{start} into #{finish}" do | |
| expect(compress(start)).to eq(finish) | |
| end | |
| end | |
| cases.each do |finish, start| | |
| it "decompresses #{start} into #{finish}" do | |
| expect(decompress(start)).to eq(finish) | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment