-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMoveToFront.java
More file actions
71 lines (57 loc) · 1.53 KB
/
MoveToFront.java
File metadata and controls
71 lines (57 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import edu.princeton.cs.algs4.BinaryStdIn;
import edu.princeton.cs.algs4.BinaryStdOut;
public class MoveToFront {
// apply move-to-front encoding, reading from standard input and writing to standard output
private static int R=256;
private static char[] init() {
char alphabet[] = new char[R];
for (int i=0; i<R; i++) {
alphabet[i] = (char)i;
}
return alphabet;
}
private static int find(char [] alphabet, char input) {
for (int i=0; i<R; i++) {
if (alphabet[i] == input) {
return i;
}
}
return 0;
}
private static void move(char [] alphabet, int id) {
char t=alphabet[id];
for (int i=id; i>0; i--) {
alphabet[i] = alphabet[i-1];
}
alphabet[0]=t;
}
public static void encode() {
char alphabet[] = init();
String input = BinaryStdIn.readString();
for (int j=0; j<input.length(); j++) {
int i=find(alphabet, input.charAt(j));
BinaryStdOut.write((byte) i);
move(alphabet, i);
}
BinaryStdOut.close();
}
// apply move-to-front decoding, reading from standard input and writing to standard output
public static void decode() {
char alphabet[] = init();
while (!BinaryStdIn.isEmpty()) {
int input = BinaryStdIn.readInt(8);
BinaryStdOut.write(alphabet[input]);
move(alphabet, input);
}
BinaryStdOut.close();
}
// 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].compareTo("-") == 0) {
encode();
} else if (args[0].compareTo("+") == 0) {
decode();
}
}
}