-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhuffman.java
More file actions
80 lines (65 loc) · 1.65 KB
/
Copy pathhuffman.java
File metadata and controls
80 lines (65 loc) · 1.65 KB
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
package april18;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.PriorityQueue;
public class huffman {
static HashMap<Character, String> enc = new HashMap<>();
static HashMap<String, Character> dec = new HashMap<>();
public static class Node implements Comparable<Node> {
char data;
int freq;
Node left;
Node right;
Node(char data, int freq) {
this.data = data;
this.freq = freq;
}
public int compareTo(Node other) {
return this.freq - other.freq;
}
}
public static void traversal(Node n, String asf) {
if (n.left == null && n.right == null) {
enc.put(n.data, asf);
dec.put(asf, n.data);
return;
}
traversal(n.left, asf + "0");
traversal(n.right, asf + "1");
}
public static void Huffman(String feeder) {
HashMap<Character, Integer> fmap = new HashMap<>();
for (int i = 0; i < feeder.length(); i++) {
char c = feeder.charAt(i);
if (fmap.containsKey(c) == true) {
int key = fmap.get(c);
key++;
fmap.put(c, key);
} else {
fmap.put(c, 1);
}
}
// System.out.println(fmap);
ArrayList<Character> keys = new ArrayList<>(fmap.keySet());
System.out.println(keys);
PriorityQueue<Node> q = new PriorityQueue<>();
for (int i = 0; i < keys.size(); i++) {
q.add(new Node(keys.get(i), fmap.get(keys.get(i))));
}
while (q.size() > 1) {
Node n1 = q.remove();
Node n2 = q.remove();
Node n3 = new Node('$', n1.freq + n2.freq);
n3.left = n1;
n3.right = n2;
q.add(n3);
}
Node root = q.remove();
traversal(root, "");
}
public static void main(String[] args) {
Huffman("aaaabbbcc");
System.out.println(enc);
System.out.println(dec);
}
}