Implementing Run Length Encoding in Java

package rle;
import java.io.*;
public class RLE {
    public static void main(String[] args) throws IOException {
        BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter line to encode:");
        String ip = obj.readLine();
        int len = ip.length();
        int i = 0;
        int c = 0;
        char f = ip.charAt(0);
        
        String op = "";
        for(;i<len;i++)
        {
            if(i+1<len)
            {
                if(ip.charAt(i) == ip.charAt(i+1))
                {
                    c++;
                }
                else
                {
                    //System.out.print(Integer.toHexString(c+1));
                    //System.out.print(f);
                    op = op + Integer.toHexString(c+1) + f;
                    c = 0;
                    f = ip.charAt(i+1);
                }
            }
            else
            {
                //System.out.print(Integer.toHexString(c+1));
                //System.out.print(f);
                op = op + Integer.toHexString(c+1) + f;
            }
        }
        
        System.out.println("Encoded line is: " + op);
        System.out.println("Length of original string: "+len);
        System.out.println("Length of encoded string: "+op.length());
        System.out.println("Compression ratio:" +(op.length()*1.0/len));
    }
}

/*
Enter line to encode:
11100000000000111111111110000010101111
Encoded line is: 31b0b1501110111041
Length of original string: 38
Length of encoded string: 18
Compression ratio:0.47368421052631576
*/

Leave a Reply

Your email address will not be published. Required fields are marked *