CLEAN CODE: RUN LENGTH ENCODING FOR STRING

By: Saurav

2018-01-02 03:08:00 UTC

Given a string, run length encoding on it.
For example, the string 'wwwwaaadexxxxxx' should be returned as "w4a3d1e1x6".

lets, write some test case first.

This is one of those problems where writing as many tests is really important.

p get_new_format('wwwwaaadexxxxxx') == "w4a3d1e1x6"
p get_new_format('xxxxxx') == "x6"
p get_new_format('aaaa') == "a4"
p get_new_format('aaaab') == "a4b1"
p get_new_format('') == ""
p get_new_format(' ') == " 1"

The idea is to have a buffer which stores current character and the count of that buffer.
At the end return a string which is made by concatenating the buffer and the count.
If there is any character which is not equal to the buffer, add the buffer and count to the final string and set the buffer to the new element and count as 1.

let's see it in code:

def get_new_format(input_string)
  iinput_string = input_string.strip
  
  return input_string if input_string.length < 1 
  
  count = 1 
  buffer = input_string[0]
  final_string = ''
  
  (1..input_string.size-1).each do |i|
    
    if buffer != input_string[i]
      final_string += buffer
      final_string += count.to_s
      buffer = input_string[i]
      count = 1
    else 
      count += 1
    end 
  end 
  
  final_string += buffer
  final_string += count.to_s
  
  return final_string
end 

p get_new_format('wwwwaaadexxxxxx') == "w4a3d1e1x6"
p get_new_format('xxxxxx') == "x6"
p get_new_format('aaaa') == "a4"
p get_new_format('aaaab') == "a4b1"
p get_new_format('') == ""
p get_new_format(' ') == " 1"

Looks good to me!


Let me know what you think!
Twitter: sprakash24oct
Linkedin

Owned & Maintained by Saurav Prakash

If you like what you see, you can help me cover server costs or buy me a cup of coffee though donation :)