Useful for testing graph algorithms
//Latest version here: https://gist.github.com/1c20bc400beabef79f390a876758bb4e.git
using System;
using System.Collections.Generic;
using System.Linq;
namespace TestGraphUtils
{
/// <summary>
/// Useful graph builder for testing algorithms
/// </summary>
public partial class TestGraphNode
{
public string Name { get; set; }
public Dictionary<object, object> Data { get; }= new Dictionary<object, object>();
public List<TestGraphNode> IncomingLinks { get; } = new List<TestGraphNode>();
public List<TestGraphNode> Links { get; } = new List<TestGraphNode>();
public TestGraphNode Link(params TestGraphNode[] nodes)
{
Links.AddRange(nodes);
foreach (var n in nodes)
{
n.IncomingLinks.Add(this);
}
return this;
}
public TestGraphNode Link(Action<TestGraphNode> afterAdd = null, Action<TestGraphNode> beforeAdd = null)
{
var n = new TestGraphNode();
beforeAdd?.Invoke(n);
var res = Link(n);
afterAdd?.Invoke(n);
return res;
}
public TestGraphNode TopParent { get { return IncomingLinks.FirstOrDefault(); } }
public int? IndexInParent { get { return TopParent?.Links.IndexOf(this); } }
public IEnumerable<TestGraphNode> GetTopParents()
{
var current = TopParent;
while (current != null)
{
yield return current;
current = current.TopParent;
}
}
public IEnumerable<TestGraphNode> GetSelfAndTopParents()
{
yield return this;
foreach (var p in GetTopParents())
{
yield return p;
}
}
public string Title { get { return Name ?? ((IndexInParent + 1)?.ToString()) ?? "(root)"; } }
public override string ToString()
{
if (TopParent == null) return Title;
return TopParent.ToString() + "\\" + Title;
}
public static TestGraphNode GenerateTestGraph()
{
var root = new TestGraphNode()
.Link()//0.1
.Link(n2 => {//0.2
n2
.Link()//0.2.1
.Link();//0.2.2
})
.Link(n3 => {
})//0.3
;
return root;
}
}
}