compressor function

given: “aaabbcca”
return: “a3b2c2a1”

def compressor(string)
	# initialize
	compressed = ''
	count = 0
	i = 0

	size = string.size

	string.each_char do |s|
		
		i += 1

		if compressed[-1].nil?
			count = 1
			compressed = s
			next
		end

		# when c[-1] = a, s = a
		if compressed[-1] == s 
			count += 1
			# last character
			if i == size
				compressed << count.to_s
			end
			next
		end

		# when c[-1] = a, s = b
		if compressed[-1] !=s
			compressed << count.to_s << s
			count = 1
			next
		end

	end
	compressed
end
Advertisements

would you like to leave a comment?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s