-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathWalk2.cs
78 lines (69 loc) · 1.97 KB
/
Walk2.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
using System.Linq;
class Walker2 {
record class Node(
string Name,
List<Node> Kids
) {
public WeakReference<Node?> Parent = new WeakReference<Node?>(null);
public Node(string name) : this(name, new()) { }
}
void InitParents(Node tree) {
foreach (var kid in tree.Kids) {
kid.Parent.SetTarget(tree);
InitParents(kid);
}
}
delegate void WalkAction(Node node, int depth);
void Walk(Node tree, WalkAction action, int depth = 0) {
action(tree, depth);
for (var i = 0; i < tree.Kids.Count; i += 1) {
var kid = tree.Kids[i];
Walk(kid, action, depth + 1);
}
}
void Print(Node tree) {
Walk(tree, (node, depth) => {
Console.WriteLine($"{"".PadLeft(2 * depth)}{node.Name}");
});
}
int CalcTotalDepth(Node tree) {
var total = 0;
Walk(tree, (_, depth) => {
total += depth;
});
return total;
}
void Process(Node intro) {
var tree = new Node("root", new List<Node> {
intro,
new("one", new List<Node> {
new("two"),
new("three"),
}),
new("four"),
});
InitParents(tree);
// Test pointer stability.
var internalIntro = tree.Kids[0];
tree.Kids.Add(new("outro"));
Print(internalIntro);
// Print tree and calculate.
Print(tree);
var totalDepth = 0;
foreach (var _ in Enumerable.Range(0, 200_000)) {
totalDepth += CalcTotalDepth(tree);
}
Console.WriteLine($"Total depth: {totalDepth}");
}
void Run() {
var intro = new Node("intro");
Process(intro);
// System.GC.Collect();
Node? root = null;
intro.Parent.TryGetTarget(out root);
Console.WriteLine(root.Name);
}
static void Main(string[] args) {
new Walker2().Run();
}
}