mirror of https://github.com/deavmi/niknaks
Compare commits
3 Commits
f49ecf1908
...
ce78102af9
Author | SHA1 | Date |
---|---|---|
Tristan B. Velloza Kildaire | ce78102af9 | |
Tristan B. Velloza Kildaire | 04edc241ad | |
Tristan B. Velloza Kildaire | 167c2b7c0d |
|
@ -666,27 +666,47 @@ public class Tree(T)
|
|||
TouchStratergy!(T) touch = toDelegate(&Nothing!(T))
|
||||
)
|
||||
{
|
||||
T[] collected;
|
||||
foreach(Tree!(T) child; this.children)
|
||||
version(unittest)
|
||||
{
|
||||
if(strat(child))
|
||||
writeln("dfs entry: ", this);
|
||||
}
|
||||
|
||||
T[] collected;
|
||||
scope(exit)
|
||||
{
|
||||
version(unittest)
|
||||
{
|
||||
// Touch
|
||||
touch(child);
|
||||
|
||||
// Visit
|
||||
collected ~= child.dfs(strat);
|
||||
writeln("leaving node ", this, " with collected ", collected);
|
||||
}
|
||||
}
|
||||
|
||||
if(strat(this))
|
||||
{
|
||||
// Touch
|
||||
touch(this);
|
||||
// Touch
|
||||
touch(this); // root[x]
|
||||
|
||||
// "Visit"
|
||||
collected ~= this.value;
|
||||
foreach(Tree!(T) child; this.children) // subtree[x],
|
||||
{
|
||||
if(strat(child))
|
||||
{
|
||||
version(unittest)
|
||||
{
|
||||
writeln("dfs, strat good for child: ", child);
|
||||
}
|
||||
|
||||
// Visit
|
||||
collected ~= child.dfs(strat, touch);
|
||||
}
|
||||
else
|
||||
{
|
||||
version(unittest)
|
||||
{
|
||||
writeln("dfs, strat ignored for child: ", child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// "Visit"
|
||||
collected ~= this.value;
|
||||
|
||||
|
||||
return collected;
|
||||
}
|
||||
|
@ -727,4 +747,56 @@ unittest
|
|||
|
||||
string[] result = treeOfStrings.dfs(strat, touch);
|
||||
writeln("dfs: ", result);
|
||||
}
|
||||
|
||||
public class VisitationTree(T) : Tree!(T)
|
||||
{
|
||||
private bool visisted;
|
||||
|
||||
this(T value)
|
||||
{
|
||||
super(value);
|
||||
}
|
||||
|
||||
public T[] linearize()
|
||||
{
|
||||
return dfs(toDelegate(&_shouldVisit), toDelegate(&_touch));
|
||||
}
|
||||
|
||||
private static bool _shouldVisit(Tree!(T) tnode)
|
||||
{
|
||||
VisitationTree!(T) vnode = cast(VisitationTree!(T))tnode;
|
||||
return vnode && !vnode.isVisited();
|
||||
}
|
||||
|
||||
private static void _touch(Tree!(T) tnode)
|
||||
{
|
||||
VisitationTree!(T) vnode = cast(VisitationTree!(T))tnode;
|
||||
if(vnode)
|
||||
{
|
||||
vnode.mark();
|
||||
}
|
||||
}
|
||||
|
||||
private void mark()
|
||||
{
|
||||
this.visisted = true;
|
||||
}
|
||||
|
||||
private bool isVisited()
|
||||
{
|
||||
return this.visisted;
|
||||
}
|
||||
}
|
||||
|
||||
unittest
|
||||
{
|
||||
VisitationTree!(string) root = new VisitationTree!(string)("root");
|
||||
|
||||
VisitationTree!(string) thing = new VisitationTree!(string)("subtree");
|
||||
root.appendNode(thing);
|
||||
thing.appendNode(root);
|
||||
|
||||
writeln(root.linearize());
|
||||
|
||||
}
|
Loading…
Reference in New Issue