Last active
December 12, 2015 00:18
-
-
Save YuriyGuts/4682853 to your computer and use it in GitHub Desktop.
A simple 1-pass algorithm for finding leaf nodes in a tree flattened to an array of dot-separated string keys. [C#-flavored pseudocode]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Precalculate levels according to separator characters. | |
var nodes = flattenedTree.Select(flatNode => new { | |
Value = flatNode.Value, | |
Level = flatNode.Value.Count(c => c == '.'), | |
IsLeaf = false | |
}).ToArray(); | |
// Find leaves by comparing the levels of each two adjacent items. | |
for (int i = 1; i < nodes.Length; i++) | |
{ | |
if (nodes[i].Level == nodes[i - 1].Level) | |
{ | |
nodes[i - 1].IsLeaf = true; | |
} | |
else if (nodes[i].Level == nodes[i - 1].Level + 1) | |
{ | |
nodes[i - 1].IsLeaf = false; | |
} | |
else if (nodes[i].Level < nodes[i - 1].Level) | |
{ | |
nodes[i - 1].IsLeaf = true; | |
nodes[i].IsLeaf = false; | |
} | |
} | |
nodes[nodes.Length - 1].IsLeaf = true; | |
/* | |
----- Random test #0 ------ | |
0 False 611 | |
1 False 611.328 | |
2 False 611.328.980 | |
3 False 611.328.980.232 | |
4 True 611.328.980.232.225 | |
4 False 611.328.980.232.498 | |
5 False 611.328.980.232.498.152 | |
6 True 611.328.980.232.498.152.300 | |
6 True 611.328.980.232.498.152.486 | |
4 True 611.328.980.232.992 | |
3 True 611.328.980.649 | |
----- Random test #1 ------ | |
0 False 988 | |
1 False 988.848 | |
2 True 988.848.328 | |
2 False 988.848.344 | |
3 True 988.848.344.438 | |
3 True 988.848.344.686 | |
----- Random test #2 ------ | |
0 True 506 | |
----- Random test #3 ------ | |
0 False 489 | |
1 True 489.374 | |
----- Random test #4 ------ | |
0 False 650 | |
1 True 650.333 | |
1 True 650.701 | |
1 False 650.946 | |
2 True 650.946.505 | |
2 False 650.946.510 | |
3 False 650.946.510.827 | |
4 True 650.946.510.827.646 | |
----- Random test #5 ------ | |
0 False 647 | |
1 True 647.367 | |
1 True 647.491 | |
----- Random test #6 ------ | |
0 False 921 | |
1 False 921.635 | |
2 True 921.635.182 | |
2 True 921.635.898 | |
2 True 921.635.902 | |
1 True 921.845 | |
----- Random test #7 ------ | |
0 False 625 | |
1 True 625.989 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment