-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCompression_3.java
94 lines (81 loc) · 2.25 KB
/
Compression_3.java
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
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Scanner;
public class Compression_3 {
static HashMap<Character, Integer> myMap = new HashMap<Character, Integer>();
HashMap<Character, String> newMap = new HashMap<Character, String>();
HashMap<Character, String> directory = new HashMap<Character, String>();
PriorityQueue1<Branch> q = new PriorityQueue1<Branch>();
Scanner scan = new Scanner(System.in);
private String file = "Avengers";
private String mapfile = "Map";
private void readFile() {
try {
BufferedReader in = new BufferedReader(new FileReader(file));
for (int c = in.read(); c!= -1; c= in.read()) {
if(!myMap.containsKey((char) c)) {
myMap.put((char)c, 1);
}
else{
myMap.put((char)c, myMap.get((char) c)+1);
}
}
in.close();
}
catch (FileNotFoundException e) {
System.out.println("File not found :( make sure file is in the project (not source code) and "
+ "has the correct name");
}
catch (IOException e) {}
}
private void mostcommon() {
for(char s: myMap.keySet()) {
Branch c = new Branch(s);
q.add(c, myMap.get(s));
}
//System.out.println(q);
}
private void tree() {
while(q.size()>1) {
Node<Branch> one = q.pop();
Node<Branch> two = q.pop();
Branch third = new Branch(one.GetInfo(), two.GetInfo());
q.add(third, (one.GetP()+two.GetP()));
}
binary(q.pop().GetInfo(), "");
System.out.println(directory);
}
public void binary(Branch b, String code) {
if(b.isLeaf) {
directory.put(b.c, code);
}
else {
binary(b.right, code+"1");
binary(b.left, code+"0");
}
}
public void map() throws IOException {
BufferedWriter map = new BufferedWriter(new FileWriter(mapfile));
map.write(directory.toString());
map.close();
}
public static void main(String[] args) throws IOException {
Compression_3 test = new Compression_3();
test.readFile();
test.mostcommon();
test.tree();
test.map();
}
}
//String s = "";
//for(char c: directory.keySet()) {
// s = c +" "+ directory.get(c) +"\n";
// map.write(s);
//}