-
Notifications
You must be signed in to change notification settings - Fork 143
/
Copy path1.hack
105 lines (94 loc) · 2.36 KB
/
1.hack
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
<<__EntryPoint>>
function main(): void {
$n = (int)(vec(\HH\global_get('argv') as Container<_>)[1] ?? 6);
$minDepth = 4;
$maxDepth = max($minDepth + 2, $n);
$stretchDepth = $maxDepth + 1;
$strechedTree = make($stretchDepth);
$strechedTree->calHash();
echo
"stretch tree of depth $stretchDepth\t root hash: ",
$strechedTree->getHash(),
" check: ",
$strechedTree->checkStr(),
PHP_EOL;
$longLivedTree = make($maxDepth);
$iterations = 1 << ($maxDepth);
do {
$sum = 0;
for ($i = 1; $i <= $iterations; ++$i) {
$t = make($minDepth);
$t->calHash();
$sum += $t->getHash();
}
echo "$iterations\t trees of depth $minDepth\t root hash sum: $sum\n";
$minDepth += 2;
$iterations >>= 2;
} while ($minDepth <= $maxDepth);
$longLivedTree->calHash();
echo
"long lived tree of depth $maxDepth\t root hash: ",
$longLivedTree->getHash(),
" check: ",
$longLivedTree->checkStr(),
PHP_EOL;
}
class Node {
public ?Node $left = null;
public ?Node $right = null;
public ?int $value = null;
public ?int $hash = null;
public function getHash(): int {
if ($this->hash is null) {
return 0;
}
return $this->hash;
}
public function checkStr(): string {
return $this->check() ? "true" : "false";
}
public function check(): bool {
if ($this->hash == null) {
return false;
} else if ($this->value != null) {
return true;
} else {
$left = $this->left;
$right = $this->right;
if ($left != null && $right != null) {
return $left->check() && $right->check();
}
}
return false;
}
public function calHash(): void {
if ($this->hash == null) {
if ($this->value != null) {
$this->hash = $this->value;
} else {
$left = $this->left;
$right = $this->right;
if ($left != null && $right != null) {
$left->calHash();
$right->calHash();
$leftHash = $left->hash;
$rightHash = $right->hash;
if ($leftHash != null && $rightHash != null) {
$this->hash = $leftHash + $rightHash;
}
}
}
}
}
}
function make(int $depth): Node {
$node = new Node();
if ($depth > 0) {
$depth -= 1;
$node->left = make($depth);
$node->right = make($depth);
} else {
$node->value = 1;
}
return $node;
}