Encoding Decoding Problem: Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent repeated successive characters as a single count and character. For example, the string “AAAABBBCCDAA” would be encoded as “4A3B2C1D2A“.
Implement run-length encoding and decoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters. You can assume the string to be decoded is valid.
def encode_string(string) encoded =  count = 0 to_check = "" string.split("").each do |i| if count == 0 to_check = i count += 1 else if i == to_check count +=1 else encoded.push(count,to_check) count = 1 to_check = i end end end encoded.push(count,to_check) return encoded.join end def decode_string(string) decoded =  i=0 while i<string.length-1 do decoded.push(string[i+1]*string[i].to_i) i+=2 end return decoded.join end encode = "AAAABBBCCDAA" puts encode_string(encode) #Output: 4A3B2C1D2A decode = "4A3B2C1D2A" puts decode_string(decode) #Output: AAAABBBCCDAA
Encoding and Decoding Problem Explanation: In encoding function encode_string, we create a list to store count and the letter, check the code for the clear view of function. In decoding function, in the decoded list pushing string[i] into integer times the next letter, i.e., pushing 4A as 4*A => AAAA. In the same way, until the loop reaches the end.
Also, see: Proven ways to make money with programming
Thank You ❤️#CodeWithNarendran