1+ using Test
2+
13# This is for the PriorityQueue
24using DataStructures
35
@@ -13,8 +15,6 @@ struct Branch
1315end
1416
1517const Node = Union{Leaf, Branch}
16- isbranch (branch:: Branch ) = true
17- isbranch (other:: T ) where {T} = false
1818
1919function codebook_recurse! (leaf:: Leaf , code:: String ,
2020 dict:: Dict{Char,String} )
3333# This outputs encoding Dict to be used for encoding
3434function create_codebook (n:: Node )
3535 codebook = Dict {Char,String} ()
36- codebook_recurse! (n, " " , codebook)
36+ if isa (n, Leaf)
37+ codebook[n. key]= " 0"
38+ else
39+ codebook_recurse! (n, " " , codebook)
40+ end
3741 return codebook
3842end
3943
@@ -85,14 +89,19 @@ function decode(huffman_tree::Node, bitstring::String)
8589 current = huffman_tree
8690 final_string = " "
8791 for i in bitstring
88- if (i == ' 1' )
89- current = current. left
92+ if isa (huffman_tree, Branch)
93+ if (i == ' 1' )
94+ current = current. left
95+ else
96+ current = current. right
97+ end
98+
99+ if (! isa (current, Branch))
100+ final_string *= string (current. key)
101+ current = huffman_tree
102+ end
90103 else
91- current = current. right
92- end
93- if (! isbranch (current))
94- final_string = final_string * string (current. key)
95- current = huffman_tree
104+ final_string *= string (huffman_tree. key)
96105 end
97106 end
98107
@@ -102,11 +111,13 @@ end
102111function two_pass_huffman (phrase:: String )
103112 huffman_tree = create_tree (phrase)
104113 codebook = create_codebook (huffman_tree)
105- println (codebook)
106114 bitstring = encode (codebook, phrase)
107115 final_string = decode (huffman_tree, bitstring)
108- println (bitstring)
109- println (final_string)
116+ return final_string
110117end
111118
112- two_pass_huffman (" bibbity bobbity" )
119+ @testset " b-string tests" begin
120+ @test two_pass_huffman (" b" ) == " b"
121+ @test two_pass_huffman (" bbbbbbbb" ) == " bbbbbbbb"
122+ @test two_pass_huffman (" bibbity bobbity" ) == " bibbity bobbity"
123+ end
0 commit comments