File tree Expand file tree Collapse file tree 2 files changed +64
-0
lines changed
src/main/java/com/thealgorithms/compression Expand file tree Collapse file tree 2 files changed +64
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments