-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathClass1.cs
96 lines (87 loc) · 2.07 KB
/
Class1.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace File_Compression
{
public class HuffmanCoding
{
PriorityQueue<string> Q = new PriorityQueue<string>();
List<HuffmanNode> nList = new List<HuffmanNode>();
public void Compress(string text)
{
HuffmanNode node = new HuffmanNode();
List<HuffmanNode> nodeList = node.GetList(text);
PriorityQueue<string> PQ = new PriorityQueue<string>();
foreach (HuffmanNode n in nodeList)
{
PQ.Enqueue(n);
}
int size = PQ.Size;
while (size >= 1)
{
HuffmanNode hNode = new HuffmanNode();
HuffmanNode a = new HuffmanNode();
HuffmanNode b = new HuffmanNode();
if (!PQ.isEmpty())
a = PQ.Dequeue();
if (!PQ.isEmpty())
b = PQ.Dequeue();
bool isA = true;
bool isB = true;
foreach (HuffmanNode n in nList)
{
if (n == a)
{
isA = false;
}
if (n == b)
{
isB = false;
}
}
if (isA && a.Symbol != null)
nList.Add(a);
if (isB && b.Symbol != null)
nList.Add(b);
hNode.Left = a;
hNode.Right = b;
hNode.Frequency = a.Frequency + b.Frequency;
hNode.Symbol = a.Symbol + b.Symbol;
hNode.Left.Parent = hNode.Left.Parent = hNode;
PQ.Enqueue(hNode);
size--;
}
nList.Reverse();
foreach (HuffmanNode n in nList)
{
AssignCode();
}
}
void AssignCode()
{
for (int i = 0; i < nList.Count && nList[i].Left != null && nList[i].Right != null; i++)
{
nList[i].Left.Code += "0";
nList[i].Right.Code += "1";
}
}
public void Display()
{
Console.WriteLine("Symbols,\tFrequency");
foreach (HuffmanNode n in nList)
{
Console.WriteLine(n.Symbol + " , " + n.Frequency + "\n");
}
}
public void DisplayCodes()
{
Console.WriteLine("Symbols,\tFrequency,\tCode");
foreach (HuffmanNode n in nList)
{
Console.WriteLine(n.Symbol + ",\t\t" + n.Frequency + ",\t\t" + n.Code + "\n");
}
}
}
}