Skip to content

Commit 9d34b4b

Browse files
committed
Add LZW and Arithmetic Coding algorithms in compression category
1 parent 3519a91 commit 9d34b4b

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.thealgorithms.compression;
2+
3+
import java.util.Map;
4+
5+
public class ArithmeticCoding {
6+
7+
public static double encode(String input, Map<Character, Double> probabilities) {
8+
double low = 0.0;
9+
double high = 1.0;
10+
11+
for (char symbol : input.toCharArray()) {
12+
double range = high - low;
13+
double cumProb = 0.0;
14+
15+
for (Map.Entry<Character, Double> entry : probabilities.entrySet()) {
16+
char current = entry.getKey();
17+
double prob = entry.getValue();
18+
double next = cumProb + prob;
19+
20+
if (symbol == current) {
21+
high = low + range * next;
22+
low = low + range * cumProb;
23+
break;
24+
}
25+
cumProb = next;
26+
}
27+
}
28+
return (low + high) / 2.0;
29+
}
30+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.thealgorithms.compression;
2+
3+
import java.util.*;
4+
5+
public class LZW {
6+
7+
public static List<Integer> compress(String input) {
8+
int dictSize = 256;
9+
Map<String, Integer> dictionary = new HashMap<>();
10+
for (int i = 0; i < 256; i++) {
11+
dictionary.put("" + (char) i, i);
12+
}
13+
14+
String w = "";
15+
List<Integer> result = new ArrayList<>();
16+
17+
for (char c : input.toCharArray()) {
18+
String wc = w + c;
19+
if (dictionary.containsKey(wc)) {
20+
w = wc;
21+
} else {
22+
result.add(dictionary.get(w));
23+
dictionary.put(wc, dictSize++);
24+
w = "" + c;
25+
}
26+
}
27+
28+
if (!w.isEmpty()) {
29+
result.add(dictionary.get(w));
30+
}
31+
32+
return result;
33+
}
34+
}

0 commit comments

Comments
 (0)