From a343e11e292c7271c30d6a2db8a7dc04d01d10eb Mon Sep 17 00:00:00 2001 From: James Schloss Date: Wed, 18 Aug 2021 03:00:26 -0400 Subject: [PATCH 1/2] fixing huffman encoding for Julia and adding Test --- .../huffman_encoding/code/julia/huffman.jl | 36 +++++++++++++------ 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/contents/huffman_encoding/code/julia/huffman.jl b/contents/huffman_encoding/code/julia/huffman.jl index 593d4b4f8..3029e9374 100644 --- a/contents/huffman_encoding/code/julia/huffman.jl +++ b/contents/huffman_encoding/code/julia/huffman.jl @@ -1,3 +1,5 @@ +using Test + # This is for the PriorityQueue using DataStructures @@ -13,8 +15,6 @@ struct Branch end const Node = Union{Leaf, Branch} -isbranch(branch::Branch) = true -isbranch(other::T) where {T} = false function codebook_recurse!(leaf::Leaf, code::String, dict::Dict{Char,String}) @@ -33,7 +33,11 @@ end # This outputs encoding Dict to be used for encoding function create_codebook(n::Node) codebook = Dict{Char,String}() - codebook_recurse!(n, "", codebook) + if isa(n, Leaf) + codebook[n.key]="0" + else + codebook_recurse!(n, "", codebook) + end return codebook end @@ -85,14 +89,19 @@ function decode(huffman_tree::Node, bitstring::String) current = huffman_tree final_string = "" for i in bitstring - if (i == '1') - current = current.left + if isa(huffman_tree, Branch) + if (i == '1') + current = current.left + else + current = current.right + end + + if (!isa(current, Branch)) + final_string *= string(current.key) + current = huffman_tree + end else - current = current.right - end - if (!isbranch(current)) - final_string = final_string * string(current.key) - current = huffman_tree + final_string *= string(huffman_tree.key) end end @@ -107,6 +116,11 @@ function two_pass_huffman(phrase::String) final_string = decode(huffman_tree, bitstring) println(bitstring) println(final_string) + return final_string end -two_pass_huffman("bibbity bobbity") +@testset "b-string tests" begin + @test two_pass_huffman("b") == "b" + @test two_pass_huffman("bbbbbbbb") == "bbbbbbbb" + @test two_pass_huffman("bibbity bobbity") == "bibbity bobbity" +end From 414abba405a4ec3c2c9fc5e2546dfb4fc9981d8b Mon Sep 17 00:00:00 2001 From: James Schloss Date: Sat, 23 Oct 2021 17:17:51 +0200 Subject: [PATCH 2/2] removing println statements --- contents/huffman_encoding/code/julia/huffman.jl | 3 --- 1 file changed, 3 deletions(-) diff --git a/contents/huffman_encoding/code/julia/huffman.jl b/contents/huffman_encoding/code/julia/huffman.jl index 3029e9374..e01fd1dfd 100644 --- a/contents/huffman_encoding/code/julia/huffman.jl +++ b/contents/huffman_encoding/code/julia/huffman.jl @@ -111,11 +111,8 @@ end function two_pass_huffman(phrase::String) huffman_tree = create_tree(phrase) codebook = create_codebook(huffman_tree) - println(codebook) bitstring = encode(codebook, phrase) final_string = decode(huffman_tree, bitstring) - println(bitstring) - println(final_string) return final_string end