MCPcopy Create free account
hub / github.com/MolinDeng/Princeton-algs4 / MoveToFront

Class MoveToFront

10Lab-Burrows Wheeler/MoveToFront.java:10–62  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

8import edu.princeton.cs.algs4.BinaryStdOut;
9
10public class MoveToFront {
11 private static final int R = 256;
12
13 private static char[] init() {
14 char[] a = new char[R];
15 for (char i = 0; i < R; i++) a[i] = i;
16 return a;
17 }
18
19 // apply move-to-front encoding, reading from standard input and writing to standard output
20 public static void encode() {
21 char[] index2Char = init();
22 while (!BinaryStdIn.isEmpty()) {
23 char c = BinaryStdIn.readChar(8);
24
25 int idx = 0;
26 for (; idx < R; idx++)
27 if (index2Char[idx] == c) break;
28 for (int i = idx; i > 0; i--)
29 index2Char[i] = index2Char[i - 1];
30 index2Char[0] = c;
31
32 BinaryStdOut.write(idx, 8);
33 }
34 BinaryStdOut.close();
35 }
36
37 // apply move-to-front decoding, reading from standard input and writing to standard output
38 public static void decode() {
39 char[] index2Char = init();
40 while (!BinaryStdIn.isEmpty()) {
41 int idx = BinaryStdIn.readChar();
42 char c = index2Char[idx];
43 for (int i = idx; i > 0; i--)
44 index2Char[i] = index2Char[i - 1];
45 index2Char[0] = c;
46
47 BinaryStdOut.write(c, 8);
48 }
49 BinaryStdOut.close();
50 }
51
52 // if args[0] is "-", apply move-to-front encoding
53 // if args[0] is "+", apply move-to-front decoding
54 public static void main(String[] args) {
55 if (args[0].equals("-")) {
56 encode();
57 }
58 else if (args[0].equals("+")) {
59 decode();
60 }
61 }
62}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected