Blogs

Run Length Encoding Algorithm in Java
Author:Dixanta Bahadur Shrestha
Run-Length Encoding (RLE), a lossless data compression technique which can transform length of data into a single data and count value in the compressed form.This technique can be useful of we have to work with large amount of data such as images or vidoes. Using this technique may not be handy for limited amount of data.
For Example
aaaaaaaaaabbbbbbbbbbbbbcccccccccccddddddddddaaaaaaaaaaaafffffff

If you look at the above example you can find same data has been repeated and will occupy larger space and size of the computer. Using RLE Algorithm technique we can transform above example into much lesser in size and space without loosing its data and can be convert compressed format into its original stage.

RLE Conversion For Example
10a13b11c10d12a7f
You can find different version of algorithm in the web, however I have written the Run-Length-Encoding Algorithm below with different approach.

        /**
        * String Run Length Encoding Algorithm
        * Author Dixanta Bahadur Shrestha
        * Creators Institute of Business & Technology
        * Lalitpur, Nepal
        */
       
       public class App{
           public static void main(String[] args){
               String text="aaaaaaaaaabbbbbbbbbbbbbcccccccccccddddddddddaaaaaaaaaaaafffffff";
               char previous=' ';
               int counter=1;
               String result="";
               for(int i=0;i<text.length();i++){
                   char c=text.charAt(i);
                   if(previous==' '){
                       previous=c;
                   }else if(previous==c){
                       counter++;
                   }else{
                       result += counter + ""+previous;
                       previous=c;
                       counter=1;
                   }
                   if(i==text.length()-1){
                       result += counter + ""+previous;
                   }
                   
               }
               System.out.println(text);
               System.out.println(result);
           }
       }
    
    

Previous