forked from contextfreecode/safety
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWalk.cs
More file actions
70 lines (62 loc) · 1.75 KB
/
Walk.cs
File metadata and controls
70 lines (62 loc) · 1.75 KB
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
using System.Linq;
using System.Runtime.InteropServices;
class Walker {
record struct Node(
string Name,
List<Node> Kids
// Node parent
) {
public Node(string name) : this(name, new()) { }
}
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"),
});
// Test pointer stability.
// var nodes = CollectionsMarshal.AsSpan(tree.Kids);
var internalIntro = tree.Kids[0];
tree.Kids.Add(new("outro"));
// tree.Kids.Clear();
// Print(nodes[0]);
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);
}
static void Main(string[] args) {
new Walker().Run();
}
}