Skip to content
Original file line number Diff line number Diff line change
@@ -0,0 +1,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;
}
}
46 changes: 46 additions & 0 deletions src/main/java/com/thealgorithms/compression/LZW.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.thealgorithms.compression;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* Implementation of LZW (Lempel–Ziv–Welch) compression algorithm.
* Reference: https://en.wikipedia.org/wiki/Lempel–Ziv–Welch
*/

public final class LZW {

private LZW() {
throw new UnsupportedOperationException("Utility class");
}

public static List<Integer> compress(String input) {
int dictSize = 256;
Map<String, Integer> dictionary = new HashMap<>();
for (int i = 0; i < 256; i++) {
dictionary.put("" + (char) i, i);
}

String w = "";
List<Integer> result = new ArrayList<>();

for (char c : input.toCharArray()) {
String wc = w + c;
if (dictionary.containsKey(wc)) {
w = wc;
} else {
result.add(dictionary.get(w));
dictionary.put(wc, dictSize++);
w = "" + c;
}
}

if (!w.isEmpty()) {
result.add(dictionary.get(w));
}

return result;
}
}