-
Notifications
You must be signed in to change notification settings - Fork 145
/
Copy path1.go
110 lines (92 loc) · 1.87 KB
/
1.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package main
import (
"fmt"
"os"
"strconv"
)
type BaseNode struct {
hash *int64
}
func (n *BaseNode) HasHash() bool {
return n.hash != nil
}
func (n *BaseNode) GetHash() int64 {
if n.hash == nil {
return -1
}
return *n.hash
}
type INode interface {
CalHash()
HasHash() bool
GetHash() int64
Check() bool
}
type Leaf struct {
BaseNode
value int64
}
func (l *Leaf) CalHash() {
if l.hash == nil {
l.hash = &l.value
}
}
func (l *Leaf) Check() bool {
return l.HasHash()
}
type Node struct {
BaseNode
left INode
right INode
}
func (n *Node) CalHash() {
if n.hash == nil {
n.left.CalHash()
n.right.CalHash()
merged := n.left.GetHash() + n.right.GetHash()
n.hash = &merged
}
}
func (n *Node) Check() bool {
if n.HasHash() {
return n.left.Check() && n.right.Check()
} else {
return false
}
}
func make(depth int) INode {
if depth <= 0 {
return &Leaf{value: 1}
}
d := depth - 1
return &Node{left: make(d), right: make(d)}
}
const minDepth = 4
func main() {
maxDepth := 5
if len(os.Args) > 1 {
if _n, err := strconv.Atoi(os.Args[1]); err == nil {
maxDepth = _n
}
}
if minDepth+2 > maxDepth {
maxDepth = minDepth + 2
}
stretchDepth := maxDepth + 1
stretchTree := make(stretchDepth)
stretchTree.CalHash()
fmt.Printf("stretch tree of depth %d\t root hash: %d check: %t\n", stretchDepth, stretchTree.GetHash(), stretchTree.Check())
longLivedTree := make(maxDepth)
for depth := minDepth; depth <= maxDepth; depth += 2 {
iterations := 1 << uint(maxDepth-depth+minDepth)
var sum int64 = 0
for i := 1; i <= iterations; i++ {
tree := make(depth)
tree.CalHash()
sum += tree.GetHash()
}
fmt.Printf("%d\t trees of depth %d\t root hash sum: %d\n", iterations, depth, sum)
}
longLivedTree.CalHash()
fmt.Printf("long lived tree of depth %d\t root hash: %d check: %t\n", maxDepth, longLivedTree.GetHash(), longLivedTree.Check())
}