This commit is contained in:
2024-12-17 01:13:07 -05:00
parent c745b21b85
commit 19f82ff0f7

View File

@@ -1,28 +1,53 @@
package huffman_coding;
import java.util.ArrayList;
import java.util.Arrays;
import tester.Tester;
class Examples {
ITree a;
ITree b;
ITree c;
ITree d;
ITree e;
ITree f;
void testTest(Tester t) {
t.checkExpect(1, 1);
ArrayList<ITree> trees;
ArrayList<ITree> treesSorted;
void init() {
a = new Leaf(12, "a");
b = new Leaf(45, "b");
c = new Leaf(5, "c");
d = new Leaf(13, "d");
e = new Leaf(9, "e");
f = new Leaf(16, "f");
trees = new ArrayList<ITree>(Arrays.asList(a, b, c, d, e, f));
treesSorted = new ArrayList<ITree>(Arrays.asList(c, e, a, d, f, b));
}
void testITreeSort(Tester t) {
init();
Util.sort(trees);
t.checkExpect(trees, treesSorted);
}
}
class Huffman {
ArrayList<String> charset; // Character set.
ArrayList<Boolean> freqs; // Relative frequencies of characters.
ArrayList<Integer> freqs; // Frequencies of characters.
Huffman(ArrayList<String> charset, ArrayList<Boolean> freqs) {
if (charset.size() != freqs.size()) throw new IllegalArgumentException(
"Character set must match frequencies."
);
Huffman(ArrayList<String> charset, ArrayList<Integer> freqs) {
if (charset.size() != freqs.size())
throw new IllegalArgumentException(
"Character set must match frequencies.");
if (charset.size() < 2) throw new IllegalArgumentException(
"Character set too small."
);
if (charset.size() < 2)
throw new IllegalArgumentException(
"Character set too small.");
this.charset = charset;
this.freqs = freqs;
@@ -30,17 +55,63 @@ class Huffman {
}
// Binary tree.
interface ITree<T> {}
interface ITree {
// Compare this and another tree, and return the lesser of the two.
ITree lesserOf(ITree n);
class Node<T> implements ITree<T> {
// Is this tree less than the given frequency?
boolean lessThan(int freq);
}
ITree<T> l;
ITree<T> r;
abstract class ATree implements ITree {
int freq; // The frequency of the tree.
Node(ITree<T> l, ITree<T> r) {
ATree(int freq) {
this.freq = freq;
}
public ITree lesserOf(ITree n) {
return n.lessThan(this.freq) ? n : this;
}
public boolean lessThan(int freq) {
return this.freq < freq;
}
}
class Node extends ATree {
// Left and right branches of tree.
ITree l, r;
Node(int freq, ITree l, ITree r) {
super(freq);
this.l = l;
this.r = r;
}
}
class Leaf<T> implements ITree<T> {}
class Leaf extends ATree {
String ch; // The character.
Leaf(int freq, String ch) {
super(freq);
this.ch = ch;
}
}
class Util {
// Sort a list of trees from least to most frequent.
static void sort(ArrayList<ITree> trees) {
}
// Insert a Tree into an ArrayList of trees already sorted in [0, i], where
// 0 <= i <= sortedTrees.size(), such that it is sorted through [0, i].
static void insert(ITree tree, ArrayList<ITree> sortedTrees, int maxIndexPossible) {
}
// Insert a Tree in an already fully sorted ArrayList of Trees.
static void insert(ITree tree, ArrayList<ITree> sortedTrees) {
}
}