Advertisement
jules0707

MoveToFront.java

Jun 7th, 2021
743
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.22 KB | None | 0 0
  1. import edu.princeton.cs.algs4.BinaryStdIn;
  2. import edu.princeton.cs.algs4.BinaryStdOut;
  3. import java.util.Arrays;
  4.  
  5. public class MoveToFront {
  6.     // apply move-to-front encoding, reading from standard input and writing to standard output
  7.     public static void encode() {
  8.         char[] seq = initializeASCII();
  9.         while (!BinaryStdIn.isEmpty()) { // read each 8-bit character c from standard input, one at a time
  10.             char c = BinaryStdIn.readChar();
  11.             int b = String.copyValueOf(seq).indexOf(c);
  12.             BinaryStdOut.write((byte) b);
  13.             seq = shiftToFront(seq, b);
  14.         }
  15.         BinaryStdOut.close();
  16.     }
  17.  
  18.     // apply move-to-front decoding, reading from standard input and writing to standard output
  19.     public static void decode() {
  20.         char[] seq = initializeASCII();
  21.         while (!BinaryStdIn.isEmpty()) { // read each 8-bit character c from standard input, one at a time
  22.             byte b = BinaryStdIn.readByte();
  23.             char c = (char) (b & 0xff);
  24.             BinaryStdOut.write(seq[c]);
  25.             seq = shiftToFront(seq, c);
  26.         }
  27.         BinaryStdOut.close();
  28.     }
  29.  
  30.     // ------------- UTILITIES ----------------//
  31.  
  32.     private static char[] initializeASCII() {
  33.         int r = 256; // extended ASCII
  34.         char[] seq = new char[r];
  35.         for (int i = 0; i < r; i++) { // Initialization of the ordered sequence of 256 extended ASCII characters
  36.             seq[i] = (char) (i & 0xff);
  37.         }
  38.         return seq;
  39.     }
  40.  
  41.     private static char[] shiftToFront(char[] seq, int idx) {
  42.         int n = seq.length;
  43.         char[] copy = Arrays.copyOf(seq, n);
  44.         char c = seq[idx];
  45.         char[] dest = new char[n];
  46.         System.arraycopy(copy, 0, dest, 1, idx);
  47.         System.arraycopy(copy, idx + 1, dest, idx + 1, n - idx - 1);
  48.         dest[0] = c;
  49.         seq = dest;
  50.         return seq;
  51.     }
  52.    
  53.     // if args[0] is "-", apply move-to-front encoding
  54.     // if args[0] is "+", apply move-to-front decoding
  55.     public static void main(String[] args) {
  56.         if (args[0].equals("-")) encode();
  57.         else if (args[0].equals("+")) decode();
  58.         else throw new IllegalArgumentException("Illegal command line argument");
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement