|
| 1 | +package com.thealgorithms.compression; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Collections; |
| 5 | +import java.util.HashMap; |
| 6 | +import java.util.List; |
| 7 | +import java.util.Map; |
| 8 | +import java.util.stream.Collectors; |
| 9 | + |
| 10 | +/** |
| 11 | + * An implementation of the Shannon-Fano algorithm for generating prefix codes. |
| 12 | + * |
| 13 | + * <p>Shannon-Fano coding is an entropy encoding technique for lossless data |
| 14 | + * compression. It assigns variable-length codes to symbols based on their |
| 15 | + * frequencies of occurrence. It is a precursor to Huffman coding and works by |
| 16 | + * recursively partitioning a sorted list of symbols into two sub-lists with |
| 17 | + * nearly equal total frequencies. |
| 18 | + * |
| 19 | + * <p>The algorithm works as follows: |
| 20 | + * <ol> |
| 21 | + * <li>Count the frequency of each symbol in the input data.</li> |
| 22 | + * <li>Sort the symbols in descending order of their frequencies.</li> |
| 23 | + * <li>Recursively divide the list of symbols into two parts with sums of |
| 24 | + * frequencies as close as possible to each other.</li> |
| 25 | + * <li>Assign a '0' bit to the codes in the first part and a '1' bit to the codes |
| 26 | + * in the second part.</li> |
| 27 | + * <li>Repeat the process for each part until a part contains only one symbol.</li> |
| 28 | + * </ol> |
| 29 | + * |
| 30 | + * <p>Time Complexity: O(n^2) in this implementation due to the partitioning logic, |
| 31 | + * or O(n log n) if a more optimized partitioning strategy is used. |
| 32 | + * Sorting takes O(n log n), where n is the number of unique symbols. |
| 33 | + * |
| 34 | + * <p>References: |
| 35 | + * <ul> |
| 36 | + * <li><a href="https://en.wikipedia.org/wiki/Shannonâ€"Fano_coding">Wikipedia: Shannonâ€"Fano coding</a></li> |
| 37 | + * </ul> |
| 38 | + */ |
| 39 | +public final class ShannonFano { |
| 40 | + |
| 41 | + /** |
| 42 | + * Private constructor to prevent instantiation of this utility class. |
| 43 | + */ |
| 44 | + private ShannonFano() { |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * A private inner class to represent a symbol and its frequency. |
| 49 | + * Implements Comparable to allow sorting based on frequency. |
| 50 | + */ |
| 51 | + private static class Symbol implements Comparable<Symbol> { |
| 52 | + final char character; |
| 53 | + final int frequency; |
| 54 | + String code = ""; |
| 55 | + |
| 56 | + Symbol(char character, int frequency) { |
| 57 | + this.character = character; |
| 58 | + this.frequency = frequency; |
| 59 | + } |
| 60 | + |
| 61 | + @Override |
| 62 | + public int compareTo(Symbol other) { |
| 63 | + return Integer.compare(other.frequency, this.frequency); // Sort descending |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * Generates Shannon-Fano codes for the symbols in a given text. |
| 69 | + * |
| 70 | + * @param text The input string for which to generate codes. Must not be null. |
| 71 | + * @return A map where keys are characters and values are their corresponding Shannon-Fano codes. |
| 72 | + */ |
| 73 | + public static Map<Character, String> generateCodes(String text) { |
| 74 | + if (text == null || text.isEmpty()) { |
| 75 | + return Collections.emptyMap(); |
| 76 | + } |
| 77 | + |
| 78 | + Map<Character, Integer> frequencyMap = new HashMap<>(); |
| 79 | + for (char c : text.toCharArray()) { |
| 80 | + frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1); |
| 81 | + } |
| 82 | + |
| 83 | + List<Symbol> symbols = new ArrayList<>(); |
| 84 | + for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) { |
| 85 | + symbols.add(new Symbol(entry.getKey(), entry.getValue())); |
| 86 | + } |
| 87 | + |
| 88 | + Collections.sort(symbols); |
| 89 | + |
| 90 | + // Special case: only one unique symbol |
| 91 | + if (symbols.size() == 1) { |
| 92 | + symbols.getFirst().code = "0"; |
| 93 | + } else { |
| 94 | + buildCodeTree(symbols, 0, symbols.size() - 1, ""); |
| 95 | + } |
| 96 | + |
| 97 | + return symbols.stream().collect(Collectors.toMap(s -> s.character, s -> s.code)); |
| 98 | + } |
| 99 | + |
| 100 | + /** |
| 101 | + * Recursively builds the Shannon-Fano code tree by partitioning the list of symbols. |
| 102 | + * Uses index-based approach to avoid sublist creation issues. |
| 103 | + * |
| 104 | + * @param symbols The sorted list of symbols to be processed. |
| 105 | + * @param start The start index of the current partition. |
| 106 | + * @param end The end index of the current partition (inclusive). |
| 107 | + * @param prefix The current prefix code being built for the symbols in this partition. |
| 108 | + */ |
| 109 | + private static void buildCodeTree(List<Symbol> symbols, int start, int end, String prefix) { |
| 110 | + // The initial check in generateCodes ensures start <= end is always true here. |
| 111 | + // The base case is when a partition has only one symbol. |
| 112 | + if (start == end) { |
| 113 | + symbols.get(start).code = prefix; |
| 114 | + return; |
| 115 | + } |
| 116 | + |
| 117 | + // Find the optimal split point |
| 118 | + int splitIndex = findSplitIndex(symbols, start, end); |
| 119 | + |
| 120 | + // Recursively process left and right partitions with updated prefixes |
| 121 | + buildCodeTree(symbols, start, splitIndex, prefix + "0"); |
| 122 | + buildCodeTree(symbols, splitIndex + 1, end, prefix + "1"); |
| 123 | + } |
| 124 | + |
| 125 | + /** |
| 126 | + * Finds the index that splits the range into two parts with the most balanced frequency sums. |
| 127 | + * This method tries every possible split point and returns the index that minimizes the |
| 128 | + * absolute difference between the two partition sums. |
| 129 | + * |
| 130 | + * @param symbols The sorted list of symbols. |
| 131 | + * @param start The start index of the range. |
| 132 | + * @param end The end index of the range (inclusive). |
| 133 | + * @return The index of the last element in the first partition. |
| 134 | + */ |
| 135 | + private static int findSplitIndex(List<Symbol> symbols, int start, int end) { |
| 136 | + // Calculate total frequency for the entire range |
| 137 | + long totalFrequency = 0; |
| 138 | + for (int i = start; i <= end; i++) { |
| 139 | + totalFrequency += symbols.get(i).frequency; |
| 140 | + } |
| 141 | + |
| 142 | + long leftSum = 0; |
| 143 | + long minDifference = Long.MAX_VALUE; |
| 144 | + int splitIndex = start; |
| 145 | + |
| 146 | + // Try every possible split point and find the one with minimum difference |
| 147 | + for (int i = start; i < end; i++) { |
| 148 | + leftSum += symbols.get(i).frequency; |
| 149 | + long rightSum = totalFrequency - leftSum; |
| 150 | + long difference = Math.abs(leftSum - rightSum); |
| 151 | + |
| 152 | + if (difference < minDifference) { |
| 153 | + minDifference = difference; |
| 154 | + splitIndex = i; |
| 155 | + } |
| 156 | + } |
| 157 | + return splitIndex; |
| 158 | + } |
| 159 | +} |
0 commit comments