Last active
May 3, 2017 19:11
-
-
Save pmunin/1c20bc400beabef79f390a876758bb4e to your computer and use it in GitHub Desktop.
Useful for testing graph algorithms
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
| //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; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment