forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HuffmanCompressor.cs
167 lines (139 loc) · 5.44 KB
/
HuffmanCompressor.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
using System;
using System.Collections.Generic;
using System.Linq;
using Algorithms.Sorters.Comparison;
using Utilities.Extensions;
namespace Algorithms.DataCompression
{
/// <summary>
/// Greedy lossless compression algorithm.
/// </summary>
public class HuffmanCompressor
{
// TODO: Use partial sorter
private readonly IComparisonSorter<ListNode> sorter;
private readonly Translator translator;
public HuffmanCompressor(IComparisonSorter<ListNode> sorter, Translator translator)
{
this.sorter = sorter;
this.translator = translator;
}
/// <summary>
/// Given an input string, returns a new compressed string
/// using huffman encoding.
/// </summary>
/// <param name="uncompressedText">Text message to compress.</param>
/// <returns>Compressed string and keys to decompress it.</returns>
public (string compressedText, Dictionary<string, string> decompressionKeys) Compress(string uncompressedText)
{
if (string.IsNullOrEmpty(uncompressedText))
{
return (string.Empty, new Dictionary<string, string>());
}
if (uncompressedText.Distinct().Count() == 1)
{
var dict = new Dictionary<string, string>
{
{ "1", uncompressedText[0].ToString() },
};
return (new string('1', uncompressedText.Length), dict);
}
var nodes = GetListNodesFromText(uncompressedText);
var tree = GenerateHuffmanTree(nodes);
var (compressionKeys, decompressionKeys) = GetKeys(tree);
return (translator.Translate(uncompressedText, compressionKeys), decompressionKeys);
}
/// <summary>
/// Finds frequency for each character in the text.
/// </summary>
/// <returns>Symbol-frequency array.</returns>
private static ListNode[] GetListNodesFromText(string text)
{
var occurenceCounts = new Dictionary<char, int>();
foreach (var ch in text)
{
if (!occurenceCounts.ContainsKey(ch))
{
occurenceCounts.Add(ch, 0);
}
occurenceCounts[ch]++;
}
return occurenceCounts.Select(kvp => new ListNode(kvp.Key, 1d * kvp.Value / text.Length)).ToArray();
}
private (Dictionary<string, string> compressionKeys, Dictionary<string, string> decompressionKeys) GetKeys(
ListNode tree)
{
var compressionKeys = new Dictionary<string, string>();
var decompressionKeys = new Dictionary<string, string>();
if (tree.HasData)
{
compressionKeys.Add(tree.Data.ToString(), string.Empty);
decompressionKeys.Add(string.Empty, tree.Data.ToString());
return (compressionKeys, decompressionKeys);
}
if (tree.LeftChild is not null)
{
var (lsck, lsdk) = GetKeys(tree.LeftChild);
compressionKeys.AddMany(lsck.Select(kvp => (kvp.Key, "0" + kvp.Value)));
decompressionKeys.AddMany(lsdk.Select(kvp => ("0" + kvp.Key, kvp.Value)));
}
if (tree.RightChild is not null)
{
var (rsck, rsdk) = GetKeys(tree.RightChild);
compressionKeys.AddMany(rsck.Select(kvp => (kvp.Key, "1" + kvp.Value)));
decompressionKeys.AddMany(rsdk.Select(kvp => ("1" + kvp.Key, kvp.Value)));
return (compressionKeys, decompressionKeys);
}
return (compressionKeys, decompressionKeys);
}
private ListNode GenerateHuffmanTree(ListNode[] nodes)
{
var comparer = new ListNodeComparer();
while (nodes.Length > 1)
{
sorter.Sort(nodes, comparer);
var left = nodes[0];
var right = nodes[1];
var newNodes = new ListNode[nodes.Length - 1];
Array.Copy(nodes, 2, newNodes, 1, nodes.Length - 2);
newNodes[0] = new ListNode(left, right);
nodes = newNodes;
}
return nodes[0];
}
/// <summary>
/// Represents tree structure for the algorithm.
/// </summary>
public class ListNode
{
public ListNode(char data, double frequency)
{
HasData = true;
Data = data;
Frequency = frequency;
}
public ListNode(ListNode leftChild, ListNode rightChild)
{
LeftChild = leftChild;
RightChild = rightChild;
Frequency = leftChild.Frequency + rightChild.Frequency;
}
public char Data { get; }
public bool HasData { get; }
public double Frequency { get; }
public ListNode? RightChild { get; }
public ListNode? LeftChild { get; }
}
public class ListNodeComparer : IComparer<ListNode>
{
public int Compare(ListNode? x, ListNode? y)
{
if (x is null || y is null)
{
return 0;
}
return x.Frequency.CompareTo(y.Frequency);
}
}
}
}