-
Notifications
You must be signed in to change notification settings - Fork 143
/
Copy path1.kt
84 lines (71 loc) · 2.12 KB
/
1.kt
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
import kotlin.math.*
const val MinDepth = 4
fun main(args: Array<String>) {
val maxDepth = if (args.size > 0) max(args[0].toInt(), MinDepth + 2) else 10
val stretchDepth = maxDepth + 1
val stretchTree = Node.create(stretchDepth)
stretchTree.calHash()
println(
"stretch tree of depth ${stretchDepth}\t root hash: ${stretchTree.getHash()} check: ${stretchTree.check()}"
)
val longLivedTree = Node.create(maxDepth)
val nResults = (maxDepth - MinDepth) / 2 + 1
for (i in 0..nResults - 1) {
val depth = i * 2 + MinDepth
val n = 1.shl(maxDepth - depth + MinDepth)
var sum = 0L
for (j in 1..n) {
val tree = Node.create(depth)
tree.calHash()
sum += tree.getHash()
}
println("${n}\t trees of depth ${depth}\t root hash sum: ${sum}")
}
longLivedTree.calHash()
println(
"long lived tree of depth ${maxDepth}\t root hash: ${longLivedTree.getHash()} check: ${longLivedTree.check()}"
)
}
class Node(val value: Long?, val left: Node?, val right: Node?) {
var hash: Long? = null
fun check(): Boolean {
if (hash != null) {
if (value != null) {
return true
}
if (left != null && right != null) {
return left.check() && right.check()
}
return false
} else {
return false
}
}
fun calHash() {
if (hash == null) {
if (value != null) {
hash = value
} else if (left != null && right != null) {
left.calHash()
right.calHash()
hash = left.getHash() + right.getHash()
}
}
}
fun getHash(): Long {
if (hash != null) {
return hash!!
} else {
return -1
}
}
companion object {
fun create(n: Int): Node {
if (n == 0) {
return Node(1, null, null)
}
val d = n - 1
return Node(null, Node.create(d), Node.create(d))
}
}
}