-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhuffman_test.go
83 lines (76 loc) · 1.71 KB
/
huffman_test.go
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package huffman
import (
"fmt"
"testing"
)
func TestBuild(t *testing.T) {
fmt.Println()
t1, t2 := Build(nil), Build([]*Node{})
if t1 != nil || t2 != nil {
t.Errorf("Got: %v, %v, want: nil, nil", t1, t2)
}
leaves := []*Node{ // From "this is an example of a huffman tree"
{Value: ' ', Count: 7},
{Value: 'a', Count: 4},
{Value: 'e', Count: 4},
{Value: 'f', Count: 3},
{Value: 'h', Count: 2},
{Value: 'i', Count: 2},
{Value: 'm', Count: 2},
{Value: 'n', Count: 2},
{Value: 's', Count: 2},
{Value: 't', Count: 2},
{Value: 'l', Count: 1},
{Value: 'o', Count: 1},
{Value: 'p', Count: 1},
{Value: 'r', Count: 1},
{Value: 'u', Count: 1},
{Value: 'x', Count: 1},
}
root := Build(leaves)
if root == nil {
t.Errorf("Got: %v, want: not nil", root)
}
Print(root)
}
func TestBuild2(t *testing.T) {
fmt.Println()
t1, t2 := Build(nil), Build([]*Node{})
if t1 != nil || t2 != nil {
t.Errorf("Got: %v, %v, want: nil, nil", t1, t2)
}
leaves := []*Node{
{Value: ' ', Count: 20},
{Value: 'a', Count: 40},
{Value: 'l', Count: 7},
{Value: 'm', Count: 10},
{Value: 'f', Count: 8},
{Value: 't', Count: 15},
}
root := Build(leaves)
if root == nil {
t.Errorf("Got: %v, want: not nil", root)
}
Print(root)
type code struct {
r uint64
bits byte
}
expected := map[ValueType]code{
'a': {0x0, 1}, // 0
'm': {0x04, 3}, // 100
'l': {0x0a, 4}, // 1010
'f': {0x0b, 4}, // 1011
't': {0x06, 3}, // 110
' ': {0x07, 3}, // 111
}
for _, leave := range leaves {
if leave.Left != nil {
continue // Not leaf
}
r, bits := leave.Code()
if exp, got := (code{r, bits}), expected[leave.Value]; exp != got {
t.Errorf("Got: %v, want: %v (leave: '%c')", got, exp, leave.Value)
}
}
}