Home > Software design >  RLE Compression method
RLE Compression method

Time:12-24

Console.WriteLine("Enter the string you would want to compress using RLE format");

string UserInput = Console.ReadLine();
int repitions = 1;

for (int i = 0; i < UserInput.Length; i  )
{
    if (UserInput[i] == UserInput[i   1])
    {
        repitions  ;
    }
    else
    {
        Console.WriteLine("{0}{1}", repitions, UserInput[i]);
        repitions = 1;
    }
}

In line 5, there is an error where it says

index was outside the bounds.

My aim is to use this compression and output the number of times the characters repeats and the type of character then move onto the next. Im not sure what is wrong here.

Im expecting a proper working RLE algorithm.

CodePudding user response:

The immediate reason of the exception is in

if (UserInput[i] == UserInput[i   1])

comparions: on last character of the UserInput, i == UserInput.Length - 1 and we have index out of range at UserInput[i 1]. We have to add an extra check for the last character:

Console.WriteLine("Enter the string you would want to compress using RLE format");
string UserInput = Console.ReadLine();

for (int i = 0, count = 1; i < UserInput.Length;   i) 
  if (i < UserInput.Length - 1 && UserInput[i] == UserInput[i   1])
    count  = 1;
  else {
    // You, probably, want to get one line string (Write instead of WriteLine)
    Console.Write($"{count}{UserInput[i]}");
    
    count = 1;
  }

A more maintable approach is to extract method for RLE:

private static string ToRle(string value) {
  if (string.IsNullOrEmpty(value))
    return value;

  StringBuilder sb = new SringBuilder(value.Length * 2);

  for (int i = 0, count = 1; i < UserInput.Length;   i) 
    if (i < UserInput.Length - 1 && UserInput[i] == UserInput[i   1])
      count  = 1;
    else {
      sb.Append(count);
      sb.Append(UserInput[i]);
    
      count = 1;
    }
  }

  return sb.ToString();
}

And then use it:

Console.WriteLine("Enter the string you would want to compress using RLE format");
string UserInput = Console.ReadLine();

Console.WriteLine(ToRle(UserInput));

CodePudding user response:

Run-length encoding (RLE) is a form of data compression in which a string is reduced by replacing sequences of identical characters with a single instance of the character followed by the number of times it appears.

For example, the string "AAAABBBCCDAA" can be compressed to "4A3B2C1D2A".

RLE can be implemented in any programming language. Here is an example of how it might be implemented in JavaScript:

f

unction encode(input) {
    let output = "";
    let count = 0;
    let current_char = input[0];
    for (let i= 0; i< input.length; i  ) 
{
        if (input[i] === current_Char) {
            count  ;
        } else {
            output  = count   current_Char;
            current_Char = input[i];
            count = 1;
        }
    }

output = count current_Char;

    return output;
}
  • Related