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 BurrowsWheeler {
- // apply Burrows-Wheeler transform,
- // reading from standard input and writing to standard output
- public static void transform() {
- String txt = BinaryStdIn.readString();
- CircularSuffixArray csa = new CircularSuffixArray(txt);
- for (int i = 0; i < txt.length(); i++) { // search i
- if (csa.index(i) == 0)
- BinaryStdOut.write(i);
- }
- for (int j = 0; j < txt.length(); j++) {
- int idx = csa.index(j);
- char ch = txt.charAt((idx - 1 + txt.length()) % txt.length());
- BinaryStdOut.write(ch);
- }
- 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 txt = BinaryStdIn.readString();
- char[] a = txt.toCharArray();
- int n = a.length;
- int r = 256;
- int[] count = new int[r + 1];
- char[] aux = new char[n]; // the sorted array
- int[] next = new int[n];
- // ==== Key Index Counting Algo ===//
- // first pass: count the frequencies of each letter in txt using the key as an index.
- for (int i = 0; i < n; i++) { // ie. the number of As, Bs, Ds, Es, Fs etc.
- count[a[i] + 1]++; // increment the count of each index[] keys
- }
- // second pass: count the cumulates
- for (int i = 0; i < r; i++) {
- count[i + 1] += count[i];
- }
- // third pass: distribute the items in sorted order. The value of next[i] is
- // exactly the same as the location in the new array where the value is being copied to.
- for (int i = 0; i < n; i++) {
- int p = count[a[i]]++;
- aux[p] = a[i];
- next[p] = i;
- }
- BinaryStdOut.write(reconstructString(first, aux, next));
- BinaryStdOut.close();
- }
- private static String reconstructString(int first, char[] aux, int[] next) {
- int n = next.length;
- char[] res = new char[n];
- int[] copy = Arrays.copyOf(next, n);
- for (int i = 0; i < n; i++) {
- res[i] = aux[first];
- first = copy[first];
- }
- return String.valueOf(res);
- }
- // if args[0] is "-", apply Burrows-Wheeler transform
- // if args[0] is "+", apply Burrows-Wheeler inverse transform
- public static void main(String[] args) {
- if (args[0].equals("-")) transform();
- else if (args[0].equals("+")) inverseTransform();
- else throw new IllegalArgumentException("Illegal command line argument");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement