diff --git a/src/main/java/com/thealgorithms/compression/ArithmeticCoding.java b/src/main/java/com/thealgorithms/compression/ArithmeticCoding.java new file mode 100644 index 000000000000..59a9147bc69f --- /dev/null +++ b/src/main/java/com/thealgorithms/compression/ArithmeticCoding.java @@ -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 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 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; + } +} diff --git a/src/main/java/com/thealgorithms/compression/LZW.java b/src/main/java/com/thealgorithms/compression/LZW.java new file mode 100644 index 000000000000..d9d2acd571b8 --- /dev/null +++ b/src/main/java/com/thealgorithms/compression/LZW.java @@ -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 compress(String input) { + int dictSize = 256; + Map dictionary = new HashMap<>(); + for (int i = 0; i < 256; i++) { + dictionary.put("" + (char) i, i); + } + + String w = ""; + List 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; + } +}