1
+ using Test
2
+
1
3
# This is for the PriorityQueue
2
4
using DataStructures
3
5
@@ -13,8 +15,6 @@ struct Branch
13
15
end
14
16
15
17
const Node = Union{Leaf, Branch}
16
- isbranch (branch:: Branch ) = true
17
- isbranch (other:: T ) where {T} = false
18
18
19
19
function codebook_recurse! (leaf:: Leaf , code:: String ,
20
20
dict:: Dict{Char,String} )
33
33
# This outputs encoding Dict to be used for encoding
34
34
function create_codebook (n:: Node )
35
35
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
37
41
return codebook
38
42
end
39
43
@@ -85,14 +89,19 @@ function decode(huffman_tree::Node, bitstring::String)
85
89
current = huffman_tree
86
90
final_string = " "
87
91
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
90
103
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)
96
105
end
97
106
end
98
107
@@ -102,11 +111,13 @@ end
102
111
function two_pass_huffman (phrase:: String )
103
112
huffman_tree = create_tree (phrase)
104
113
codebook = create_codebook (huffman_tree)
105
- println (codebook)
106
114
bitstring = encode (codebook, phrase)
107
115
final_string = decode (huffman_tree, bitstring)
108
- println (bitstring)
109
- println (final_string)
116
+ return final_string
110
117
end
111
118
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