Posts Huffman Code With Array
Post
Cancel

Huffman Code With Array

Introduction

View Instructions.

Alternatively, see comments.

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.lang.*;
import java.util.*;
import java.lang.Math;
/**
 * @author  Don Allen
 */
class HuffmanCodeWithArray
{
    private static String[] letterTree = new String[69];

    public HuffmanCodeWithArray(String[] myTree)
    {
        letterTree = myTree;
    }

    /*
     * remember:  0 goes left (lousy .... 
     *            1 goes right :)
     *            a space in message correspnds to a space in the return value
     *   @return 
     */
    public String getHuffmanMessage(String message)
    {
        String ans = "";
        int currentIndex = 1;
        for(int i = 0; i<message.length(); i++)
        {
          if(message.charAt(i)==' ')
          {
            ans = ans + " ";
            currentIndex = 1;
            continue;
          }
          if(message.charAt(i)=='0')
          {
            currentIndex = currentIndex*2;
            System.out.println(currentIndex);
          }
          else
          {
            currentIndex = currentIndex*2+1;
            System.out.println(currentIndex);
          }
          
          
          if(letterTree[currentIndex]!=null)
          {
            ans = ans + letterTree[currentIndex];
            currentIndex = 1;
          } 
          
        }
        return ans;
    }
}
This post is licensed under CC BY 4.0