Advertisement
NyteOwlDave

Run Length Encoding

Jan 20th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.62 KB | None | 0 0
  1.    public static void main(String[] args) throws Exception {
  2.  
  3.       Scanner kb = new Scanner(System.in);
  4.       System.out.println("Input: ");
  5.       String str = kb.nextLine();
  6.  
  7.       String Encoded = "";
  8.  
  9.       char ch=0;
  10.       char oldCh=0;
  11.       int count=0;
  12.       int index=0;
  13.  
  14.       // Loop though the entire string
  15.       while (index < str.length()) {
  16.           // Grab next character and save it twice
  17.           ch = str.charAt(index);
  18.           // Set run length to 1
  19.           count=1;
  20.           // Look ahead (if possible)
  21.           if ((index+1) < str.length()) {
  22.               // Save for comparison
  23.               oldCh = ch;
  24.               // Bump index
  25.               index++;
  26.               // Fetch next character
  27.               ch = str.charAt(index);
  28.               // Calculate run length
  29.               while ((ch == oldCh) && (index < str.length())) {
  30.                   count++;  // Bump count
  31.                   index++;  // Bump index
  32.                   ch = str.charAt(index);   // Grab next char
  33.                  
  34.                   // NOTE: Most run length encoding algorithms use
  35.                   // a maximum run length, so I'll just toss this in there
  36.                   // https://en.wikipedia.org/wiki/Run-length_encoding
  37.                   if (count > 255) {
  38.                       throw new Exception("Exceeded maximum run length (255)");
  39.                   }
  40.               }
  41.               // Back up, and regurgitate the look ahead character
  42.               index--;
  43.               ch = oldCh;
  44.           }
  45.           // Emit run length only if required
  46.           if (count > 1) {
  47.               Encoded += count;
  48.           }
  49.           // Emit character
  50.           Encoded += ch;
  51.           // Move to next index
  52.           index++;
  53.       }
  54.      
  55.       System.out.println("Encoded: " + Encoded);
  56.    }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement