Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import edu.princeton.cs.algs4.BinaryStdIn;
- import edu.princeton.cs.algs4.BinaryStdOut;
- import java.util.Arrays;
- public class MoveToFront {
- // apply move-to-front encoding, reading from standard input and writing to standard output
- public static void encode() {
- char[] seq = initializeASCII();
- while (!BinaryStdIn.isEmpty()) { // read each 8-bit character c from standard input, one at a time
- char c = BinaryStdIn.readChar();
- int b = String.copyValueOf(seq).indexOf(c);
- BinaryStdOut.write((byte) b);
- seq = shiftToFront(seq, b);
- }
- BinaryStdOut.close();
- }
- // apply move-to-front decoding, reading from standard input and writing to standard output
- public static void decode() {
- char[] seq = initializeASCII();
- while (!BinaryStdIn.isEmpty()) { // read each 8-bit character c from standard input, one at a time
- byte b = BinaryStdIn.readByte();
- char c = (char) (b & 0xff);
- BinaryStdOut.write(seq[c]);
- seq = shiftToFront(seq, c);
- }
- BinaryStdOut.close();
- }
- // ------------- UTILITIES ----------------//
- private static char[] initializeASCII() {
- int r = 256; // extended ASCII
- char[] seq = new char[r];
- for (int i = 0; i < r; i++) { // Initialization of the ordered sequence of 256 extended ASCII characters
- seq[i] = (char) (i & 0xff);
- }
- return seq;
- }
- private static char[] shiftToFront(char[] seq, int idx) {
- int n = seq.length;
- char[] copy = Arrays.copyOf(seq, n);
- char c = seq[idx];
- char[] dest = new char[n];
- System.arraycopy(copy, 0, dest, 1, idx);
- System.arraycopy(copy, idx + 1, dest, idx + 1, n - idx - 1);
- dest[0] = c;
- seq = dest;
- return seq;
- }
- // if args[0] is "-", apply move-to-front encoding
- // if args[0] is "+", apply move-to-front decoding
- public static void main(String[] args) {
- if (args[0].equals("-")) encode();
- else if (args[0].equals("+")) decode();
- else throw new IllegalArgumentException("Illegal command line argument");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement