forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArithmeticCoding.java
More file actions
39 lines (31 loc) · 1.07 KB
/
ArithmeticCoding.java
File metadata and controls
39 lines (31 loc) · 1.07 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
package com.thealgorithms.compression;
import java.util.Map;
/**
* Implementation of Arithmetic Coding algorithm.
* Reference: https://en.wikipedia.org/wiki/Arithmetic_coding
*/
public final class ArithmeticCoding {
private ArithmeticCoding() {
throw new UnsupportedOperationException("Utility class");
}
public static double encode(String input, Map<Character, Double> probabilities) {
double low = 0.0;
double high = 1.0;
for (char symbol : input.toCharArray()) {
double range = high - low;
double cumProb = 0.0;
for (Map.Entry<Character, Double> entry : probabilities.entrySet()) {
char current = entry.getKey();
double prob = entry.getValue();
double next = cumProb + prob;
if (symbol == current) {
high = low + range * next;
low = low + range * cumProb;
break;
}
cumProb = next;
}
}
return (low + high) / 2.0;
}
}