-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathBurrowsWheeler.java
More file actions
97 lines (80 loc) · 2.77 KB
/
BurrowsWheeler.java
File metadata and controls
97 lines (80 loc) · 2.77 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package assignment5;
import edu.princeton.cs.algs4.BinaryStdIn;
import edu.princeton.cs.algs4.BinaryStdOut;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
public class BurrowsWheeler {
private static final int R = 256;
// apply Burrows-Wheeler transform,
// reading from standard input and writing to standard output
public static void transform() {
String input = BinaryStdIn.readString();
BinaryStdIn.close();
CircularSuffixArray circularSuffixArray = new CircularSuffixArray(input);
int first = 0;
char[] output = new char[input.length()];
for (int i = 0; i < circularSuffixArray.length(); i++) {
if (circularSuffixArray.index(i) == 0) {
first = i;
output[i] = input.charAt(circularSuffixArray.length() - 1);
} else {
output[i] = input.charAt(circularSuffixArray.index(i) - 1);
}
}
BinaryStdOut.write(first);
BinaryStdOut.write(new String(output));
BinaryStdOut.close();
}
// apply Burrows-Wheeler inverse transform,
// reading from standard input and writing to standard output
public static void inverseTransform() {
int first = BinaryStdIn.readInt();
String s = BinaryStdIn.readString();
BinaryStdIn.close();
char[] firstChars = s.toCharArray();
indexSort(firstChars);
Map<Character, Queue<Integer>> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
Queue<Integer> queue = map.getOrDefault(ch, new LinkedList<>());
if (queue == null) {
queue = new LinkedList<>();
}
queue.add(i);
map.put(ch, queue);
}
int[] next = new int[s.length()];
for (int i = 0; i < next.length; i++) {
// noinspection ConstantConditions
next[i] = map.get(firstChars[i]).poll();
}
for (int i = 0; i < s.length(); i++) {
BinaryStdOut.write(firstChars[first]);
first = next[first];
}
BinaryStdOut.close();
}
private static void indexSort(char[] array) {
int[] count = new int[R + 1];
char[] aux = new char[array.length];
for (char c : array) {
count[c + 1]++;
}
for (int r = 0; r < R; r++) {
count[r + 1] += count[r];
}
for (char c : array) {
aux[count[c]++] = c;
}
System.arraycopy(aux, 0, array, 0, array.length);
}
public static void main(String[] args) {
if (args[0].equals("-")) {
transform();
} else {
inverseTransform();
}
}
}