Question

In: Computer Science

In C#, write a method that adds a Huffman tree (implemented via a minimum priority queue)...

In C#, write a method that adds a Huffman tree (implemented via a minimum priority queue) to a dictionary table. Include any necessary fields/properties, but keep the functionality within one single method.

Solutions

Expert Solution

Code for creating the node.

Node.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace HuffmanTest
{
    public class Node
    {
        public char Symbol { get; set; }
        public int Frequency { get; set; }
        public Node Right { get; set; }
        public Node Left { get; set; }
 
        public List<bool> Traverse(char symbol, List<bool> data)
        {
            // Leaf
            if (Right == null && Left == null)
            {
                if (symbol.Equals(this.Symbol))
                {
                    return data;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                List<bool> left = null;
                List<bool> right = null;
 
                if (Left != null)
                {
                    List<bool> leftPath = new List<bool>();
                    leftPath.AddRange(data);
                    leftPath.Add(false);
 
                    left = Left.Traverse(symbol, leftPath);
                }
 
                if (Right != null)
                {
                    List<bool> rightPath = new List<bool>();
                    rightPath.AddRange(data);
                    rightPath.Add(true);
                    right = Right.Traverse(symbol, rightPath);
                }
 
                if (left != null)
                {
                    return left;
                }
                else
                {
                    return right;
                }
            }
        }
    }
}

Main code for adding the tree to a dictionary:

HuffmanTree.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
 
namespace HuffmanTest
{
    public class HuffmanTree
    {
        private List<Node> nodes = new List<Node>();
        public Node Root { get; set; }
        public Dictionary<char, int> Frequencies = new Dictionary<char, int>();
 
        public void Build(string source)
        {
            for (int i = 0; i < source.Length; i++)
            {
                if (!Frequencies.ContainsKey(source[i]))
                {
                    Frequencies.Add(source[i], 0);
                }
 
                Frequencies[source[i]]++;
            }
 
            foreach (KeyValuePair<char, int> symbol in Frequencies)
            {
                nodes.Add(new Node() { Symbol = symbol.Key, Frequency = symbol.Value });
            }
 
            while (nodes.Count > 1)
            {
                List<Node> orderedNodes = nodes.OrderBy(node => node.Frequency).ToList<Node>();
 
                if (orderedNodes.Count >= 2)
                {
                    // Take first two items
                    List<Node> taken = orderedNodes.Take(2).ToList<Node>();
 
                    // Create a parent node by combining the frequencies
                    Node parent = new Node()
                    {
                        Symbol = '*',
                        Frequency = taken[0].Frequency + taken[1].Frequency,
                        Left = taken[0],
                        Right = taken[1]
                    };
 
                    nodes.Remove(taken[0]);
                    nodes.Remove(taken[1]);
                    nodes.Add(parent);
                }
 
                this.Root = nodes.FirstOrDefault();
 
            }
 
        }
 
        public BitArray Encode(string source)
        {
            List<bool> encodedSource = new List<bool>();
 
            for (int i = 0; i < source.Length; i++)
            {
                List<bool> encodedSymbol = this.Root.Traverse(source[i], new List<bool>());
                encodedSource.AddRange(encodedSymbol);
            }
 
            BitArray bits = new BitArray(encodedSource.ToArray());
 
            return bits;
        }
 
        public string Decode(BitArray bits)
        {
            Node current = this.Root;
            string decoded = "";
 
            foreach (bool bit in bits)
            {
                if (bit)
                {
                    if (current.Right != null)
                    {
                        current = current.Right;
                    }
                }
                else
                {
                    if (current.Left != null)
                    {
                        current = current.Left;
                    }
                }
 
                if (IsLeaf(current))
                {
                    decoded += current.Symbol;
                    current = this.Root;
                }
            }
 
            return decoded;
        }
 
        public bool IsLeaf(Node node)
        {
            return (node.Left == null && node.Right == null);
        }
 
    }
}

A testing code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
 
namespace HuffmanTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter the string:");
            string input = Console.ReadLine();
            HuffmanTree huffmanTree = new HuffmanTree();
 
            // Build the Huffman tree
            huffmanTree.Build(input);
 
            // Encode
            BitArray encoded = huffmanTree.Encode(input);
 
            Console.Write("Encoded: ");
            foreach (bool bit in encoded)
            {
                Console.Write((bit ? 1 : 0) + "");
            }
            Console.WriteLine();
 
            // Decode
            string decoded = huffmanTree.Decode(encoded);
 
            Console.WriteLine("Decoded: " + decoded);
 
            Console.ReadLine();
        }
    }
}


Related Solutions

What are the differences between a maximum priority queue and a minimum priority queue?
What are the differences between a maximum priority queue and a minimum priority queue?
write C program to implement the priority queue with the operation insert
write C program to implement the priority queue with the operation insert
Write a C program to implement the priority queue with the operations insert and extractmax. Sample...
Write a C program to implement the priority queue with the operations insert and extractmax. Sample : ====Menu==== insert extractmax display exit Enter your choice: 1 Input a number: 2 enter any key to go to main menu ====Menu==== insert extractmax display exit Enter your choice: 1 Input a number: 4 enter any key to go to main menu ====Menu==== insert extractmax display exit Enter your choice: 1 Input a number: 6 enter any key to go to main menu...
Write a c++program using queue to find the minimum value in a queue. Use the above...
Write a c++program using queue to find the minimum value in a queue. Use the above program for implementing queue. You must use dequeue function to read values from queue.  
Implement the minimum priority queue UnsortedMPQ (using vector) that is a child class of the provided...
Implement the minimum priority queue UnsortedMPQ (using vector) that is a child class of the provided MPQ class. The functions from MPQ that are virtual function (remove min(), is empty(), min(), and insert()) must be implemented in the child classes. The functions remove min() and min() should throw an exception if the minimum priority queue is empty. For the UnsortedMPQ class, you will use a vector to implement the minimum priority queue functions. The insert() function should be O(1) and...
Write a c or matlab text code(to be copied ) for Huffman coder and Huffman decoder...
Write a c or matlab text code(to be copied ) for Huffman coder and Huffman decoder that asks the user to enter the string and output the Huffman code for every letter and a code for encoding that will have every letter and its Huffman code and output all the possibilities for the real string. you must show a screen of an input and the output for both the encoder and the decoder
Write a java class for a Priority Queue. Use an arraylist, and include enque, deque, and...
Write a java class for a Priority Queue. Use an arraylist, and include enque, deque, and a method to get all the values of the queue. (This is not writing a file implementing the java class PriorityQueue, but rather you are writing a program that is a priority queue).
Building a Priority Queue in C++ using a min-heap. Not using C++ Standard Template Library. Trying...
Building a Priority Queue in C++ using a min-heap. Not using C++ Standard Template Library. Trying to understand how this works. Thank you
Language C++ Implement a Priority Queue with a Binary HEAP. Use a Max Heap. Create a...
Language C++ Implement a Priority Queue with a Binary HEAP. Use a Max Heap. Create a class called Node: Have a Name and Priority.Data set - 10 is the highest priority, 1 is lowest priority. Enqueue and dequeue in the following order. Function  Name, Priority Enqueue  Joe, 3 Enqueue  Fred,1 Enqueue Tuyet,9 Enqueue  Jose, 6 Dequeue Enqueue  Jing, 2 Enqueue  Xi, 5 Enqueue  Moe, 3 DequeueEnqueue  Miko, 7 Enqueue Vlady, 8 Enqueue Frank, 9 Enqueue  Anny, 3 DequeueEnqueue  Xi, 2 Enqueue  Wali, 2 Enqueue  xChe, 6 Enqueue  xVerra, 8 Dequeue Dequeue Dequeue Dequeue...
write a java program to Implement a Priority Queue using a linked list. Include a main...
write a java program to Implement a Priority Queue using a linked list. Include a main method demonstrating enqueuing and dequeuing several numbers, printing the list contents for each.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT