Created
May 28, 2013 22:15
-
-
Save hrp/5666577 to your computer and use it in GitHub Desktop.
WJ's homework.
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
require './string' | |
describe "String#condensify" do | |
it "encodes a string" do | |
input = "AAASSSDDDDRDDSASSDDDSSSAD" | |
output = "3A3S4DR2DSA2S3D3SAD" | |
input.condensify.should == output | |
end | |
it "encodes a string with no repeats" do | |
input = "ABCDEFG" | |
input.condensify.should == input | |
end | |
end |
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
class String | |
def condensify | |
split_by_repeating.map! do |item| | |
if item.length > 1 | |
"#{item.length}#{item[0]}" | |
else | |
item | |
end | |
end.join | |
end | |
def split_by_repeating | |
hero = [] | |
self.each_char do |char| | |
if hero.last && hero.last[0] == char | |
hero[hero.length-1] = hero.last + char | |
else | |
hero << char | |
end | |
end | |
hero | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment