-
Notifications
You must be signed in to change notification settings - Fork 146
/
Copy path1.cs
99 lines (88 loc) · 2.77 KB
/
1.cs
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
using System;
class MerkleTrees
{
class TreeNode
{
public long? value;
public long? hash;
public TreeNode left;
public TreeNode right;
public TreeNode(long? value, TreeNode left = null, TreeNode right = null)
{
this.value = value;
this.left = left;
this.right = right;
}
public static TreeNode Create(int d)
{
return d == 0 ? new TreeNode(1L, null, null)
: new TreeNode(null, Create(d - 1), Create(d - 1));
}
public bool Check()
{
if (hash != null)
{
if (value != null)
{
return true;
}
else if (left != null && right != null)
{
return left.Check() && right.Check();
}
}
return false;
}
public long GetHash()
{
if (hash.Value is long v)
{
return v;
}
return default;
}
public void CalHash()
{
if (hash == null)
{
if (value.HasValue)
{
hash = value;
}
else if (left != null && right != null)
{
left.CalHash();
right.CalHash();
hash = left.GetHash() + right.GetHash();
}
}
}
}
const int MinDepth = 4;
public static void Main(string[] args)
{
var maxDepth = args.Length == 0 ? 10
: Math.Max(MinDepth + 2, int.Parse(args[0]));
var stretchDepth = maxDepth + 1;
var stretchTree = TreeNode.Create(stretchDepth);
stretchTree.CalHash();
Console.WriteLine($"stretch tree of depth {stretchDepth}\t root hash: {stretchTree.GetHash()} check: {stretchTree.Check().ToString().ToLowerInvariant()}");
var longLivedTree = TreeNode.Create(maxDepth);
var nResults = (maxDepth - MinDepth) / 2 + 1;
for (int i = 0; i < nResults; i++)
{
var depth = i * 2 + MinDepth;
var n = (1 << maxDepth - depth + MinDepth);
var sum = 0L;
for (int j = 0; j < n; j++)
{
var tree = TreeNode.Create(depth);
tree.CalHash();
sum += tree.GetHash();
}
Console.WriteLine($"{n}\t trees of depth {depth}\t root hash sum: {sum}");
}
longLivedTree.CalHash();
Console.WriteLine($"long lived tree of depth {maxDepth}\t root hash: {longLivedTree.GetHash()} check: {longLivedTree.Check().ToString().ToLowerInvariant()}");
}
}