public Tree(SortedSet <Symbol> symbols) { // Initialize nodes list SortedSet <TreeNode> nodes = new SortedSet <TreeNode>(); foreach (Symbol symbol in symbols) { nodes.Add(new TreeNodeLeaf(symbol)); } // Special case because merge won't work if (nodes.Count == 1) { root = new TreeNodeInternal(); root.next[0] = nodes.First(); root.next[1] = new TreeNodeLeaf(new CharSymbol(0, 0)); // TODO: Terrible but I do not care return; } // Create tree from Nodes while (nodes.Count > 1) { // Merge 2 nodes together TreeNode node0 = nodes.Min(); nodes.Remove(node0); TreeNode node1 = nodes.Min(); nodes.Remove(node1); TreeNodeInternal mergedNode = new TreeNodeInternal(node0, node1); nodes.Add(mergedNode); } root = nodes.First() as TreeNodeInternal; }
public DecodeState(BinaryWriter output, Tree tree) { this.output = output; this.tree = tree; writtenBytes = 0; node = tree.root; }
public void ParseBit(bool bit) { TreeNode next = node.next[bit ? 1 : 0]; // Continue parsing if (next is TreeNodeInternal inter) { node = inter; } // Output byte from leaf, run away else if (next is TreeNodeLeaf leaf) { leaf.symbol.Write(output); node = tree.root; writtenBytes++; } }
public Tree(Dictionary <BinaryCode, Symbol> codes) { root = new TreeNodeInternal(); // Recreate Tree from provided BinaryCodes foreach (KeyValuePair <BinaryCode, Symbol> entry in codes) { BinaryCode code = entry.Key; Symbol sym = entry.Value; TreeNodeInternal node = root; TreeNodeInternal prev = null; // Traverse the tree and create necessary internal nodes on fly // FIXME: Dirty but idk how to fix int bitint = 0; foreach (bool bit in code) { prev = node; bitint = bit ? 1 : 0; if (node.next[bitint] == null) { node.next[bitint] = new TreeNodeInternal(); } if (node.next[bitint] is TreeNodeInternal inter) { node = inter; } else { throw new ArgumentException("Invalid Code!"); } } prev.next[bitint] = new TreeNodeLeaf(sym); } }