-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathhuffman.ts
38 lines (33 loc) · 1.05 KB
/
huffman.ts
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
const MinHeap = require('min-heap');
import { range } from '../../utils';
export interface Frequency {
char: string;
frequency: number;
}
/**
* Return a Huffman Tree for the prefix codes. See the snapshot in `__snapshots`
* to have a visual rappresentation.
* @url https://en.wikipedia.org/wiki/Huffman_coding
*
* Time complexity: O(n*lg(n))
* @param frequences Characters frequencies
*/
export function huffman(frequences: Frequency[]) {
/**
* Create a min priority queue with min-heap. An almost identical implementation
* can be found in 'algorithms/misc/priority-queue' but for max priority.
*/
const queue = new MinHeap((a: Frequency, b: Frequency) => a.frequency - b.frequency);
frequences.forEach(freq => queue.insert(freq));
range(0, frequences.length - 2).forEach(() => {
const left: Frequency = queue.removeHead();
const right: Frequency = queue.removeHead();
const merged = {
frequency: left.frequency + right.frequency,
left,
right,
};
queue.insert(merged);
});
return queue.removeHead();
}