//TODO: Maybe cache? //Huffman's coding with weight=1 for all. Using the O(n) described on wikipedia. // private void GenerateCodes() { StateMappings = null; //one possible state, no need for codes if (PossibleStates.Count == 1) return; StateMappings = new SortedDictionary<string, string>(); LinkedList<Node> startQueue = new LinkedList<Node>(); LinkedList<Node> endQueue = new LinkedList<Node>(); foreach (string state in PossibleStates.Select(x => x.Item1)) { startQueue.AddLast(new Node { State = state }); } while (startQueue.Count > 1) { Node newNode = new Node(); newNode.LeftChild = startQueue.First(); startQueue.RemoveFirst(); newNode.RightChild = startQueue.First(); startQueue.RemoveFirst(); endQueue.AddLast(newNode); } //one left; there must be at least 1 node in endqueue if (startQueue.Count == 1) { Node newNode = new Node(); newNode.LeftChild = startQueue.First(); startQueue.RemoveFirst(); newNode.RightChild = endQueue.First(); endQueue.RemoveFirst(); endQueue.AddLast(newNode); } //now we know that startQueue is empty and endqueue has at least 1 node. while (endQueue.Count > 1) { Node newNode = new Node(); newNode.LeftChild = endQueue.First(); endQueue.RemoveFirst(); newNode.RightChild = endQueue.First(); endQueue.RemoveFirst(); endQueue.AddLast(newNode); } //now we have 1 node left. the root node. //now to generate the codes by walking the tree. string code = ""; BuildCode(endQueue.First(), code); ShortestCode = StateMappings.Keys.OrderByDescending(s => s.Length).Last().Length; LongestCode = StateMappings.Keys.OrderByDescending(s => s.Length).First().Length; }
public Node() { rChild = lChild = null; }
/*private void Count(Node n) { if (n == null) return; if (n.LeftChild == null && n.RightChild == null) { return; } Count(n.LeftChild); Count(n.RightChild); }*/ private void BuildCode(Node n, string code) { //leaf, we need a code if (n.LeftChild == null && n.RightChild == null) { //map it StateMappings.Add(code, n.State); } //if we have a left child, add 0 to the code if (n.LeftChild != null) { BuildCode(n.LeftChild, code + "0"); } if (n.RightChild != null) { BuildCode(n.RightChild, code + "1"); } }