*URGENT* Node was Null Error??? (how do i fix error on line 54 in 3rd code file? (3rd code block)

  • Thread starter Thread starter goofy_goober
  • Start date Start date
G

goofy_goober

Guest
using System.Collections.Generic;
using System.Linq;

namespace Huffman1
{
internal class PriorityQueue<T>
{
private readonly SortedDictionary<int, Queue<T>> _sortedDictionary = new SortedDictionary<int, Queue<T>>();

public int Count { get; private set; }

public void Enqueue(T item, int priority)
{
++Count;
if (!_sortedDictionary.ContainsKey(priority)) _sortedDictionary[priority] = new Queue<T>();
_sortedDictionary[priority].Enqueue(item);
}

public T Dequeue()
{
--Count;
var item = _sortedDictionary.First();
if (item.Value.Count == 1) _sortedDictionary.Remove(item.Key);
return item.Value.Dequeue();
}
}
}


// HuffmanNode.cs
namespace Huffman1
{
internal class HuffmanNode
{
public HuffmanNode Parent { get; set; }
public HuffmanNode Left { get; set; }
public HuffmanNode Right { get; set; }
public char Value { get; set; }
public int Count { get; set; }
}
}


using System.Collections;
using System.Collections.Generic;

namespace Huffman1
{
internal class HuffmanTree
{
private readonly HuffmanNode _root;
private IDictionary counts;

public HuffmanTree(IEnumerable<KeyValuePair<char, int>> counts)
{
var priorityQueue = new PriorityQueue<HuffmanNode>();

foreach (KeyValuePair<char, int> kvp in counts)
{
priorityQueue.Enqueue(new HuffmanNode { Value = kvp.Key, Count = kvp.Value }, kvp.Value);
}

while (priorityQueue.Count > 1)
{
HuffmanNode n1 = priorityQueue.Dequeue();
HuffmanNode n2 = priorityQueue.Dequeue();
var n3 = new HuffmanNode { Left = n1, Right = n2, Count = n1.Count + n2.Count };
n1.Parent = n3;
n2.Parent = n3;
priorityQueue.Enqueue(n3, n3.Count);
}

_root = priorityQueue.Dequeue();
}

public HuffmanTree(IDictionary counts)
{
this.counts = counts;
}

public IDictionary<char, string> CreateEncodings()
{
var encodings = new Dictionary<char, string>();
Encode(_root, "", encodings);
return encodings;
}

private void Encode(HuffmanNode node, string path, IDictionary<char, string> encodings)
{
if (node?.Left != null)
{
Encode(node.Left, path + "0", encodings);
Encode(node.Right, path + "1", encodings);
}
else
{
encodings.Add(node.Value,path);
}
}
}
}


using System;
using System.Collections;
using System.Collections.Generic;

namespace Huffman1
{
class Program
{
static void Main(string[] args)
{
IDictionary counts = new Dictionary<char, int>();
// ac bca ba z
counts.Add(' ', 3);
counts.Add('b', 2);
counts.Add('a', 3);
counts.Add('c', 2);
counts.Add('z', 1);
counts.Add('\n', 1);
HuffmanTree tree = new HuffmanTree(counts);
IDictionary<char, string> encodings = tree.CreateEncodings();

foreach (KeyValuePair<char, string> kvp in encodings)
{
Console.WriteLine((kvp.Key == '\n' ? "EOF" : kvp.Key.ToString()) + ":\t" + kvp.Value);
}

Console.ReadLine();
}
}
}

Continue reading...
 
Back
Top