Commits

Mark Heath committed f17cb52

ability to find root and leaf nodes in a graph

Comments (0)

Files changed (4)

GraphPad.Tests/GraphPad.Tests.csproj

   </ItemGroup>
   <ItemGroup>
     <Compile Include="GraphBuilderTests.cs" />
+    <Compile Include="GraphTests.cs" />
     <Compile Include="NodeInfoTests.cs" />
     <Compile Include="TokenizerTests.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />

GraphPad.Tests/GraphTests.cs

+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using NUnit.Framework;
+using GraphPad.Logic;
+
+namespace GraphPad.Tests
+{
+    [TestFixture]
+    public class GraphTests
+    {
+        [Test]
+        public void CanFindRoot()
+        {
+            NodeInfo root = new NodeInfo() { Name = "root" };
+            NodeInfo a = new NodeInfo() { Name = "a" };
+            root.AddChild(a);
+            Graph g = new Graph();
+            g.Nodes.Add(root);
+            g.Nodes.Add(a);
+
+            Assert.AreEqual(1, g.RootNodes.Count());
+            Assert.AreEqual(root, g.RootNodes.First());
+
+        }
+
+        [Test]
+        public void CanFindLeaf()
+        {
+            NodeInfo root = new NodeInfo() { Name = "root" };
+            NodeInfo middle = new NodeInfo() { Name = "middle" };
+            NodeInfo leaf = new NodeInfo() { Name = "leaf" };
+            root.AddChild(middle);
+            middle.AddChild(leaf);
+            Graph g = new Graph();
+            g.Nodes.Add(root);
+            g.Nodes.Add(middle);
+            g.Nodes.Add(leaf);
+
+            Assert.AreEqual(1, g.LeafNodes.Count());
+            Assert.AreEqual(leaf, g.LeafNodes.First());
+
+        }
+    }
+}

GraphPad/Logic/Graph.cs

             this.nodes = new List<NodeInfo>();
         }
 
+        public IEnumerable<NodeInfo> RootNodes { get { return nodes.Where(n => n.IsRootNode()); } }
+        public IEnumerable<NodeInfo> LeafNodes { get { return nodes.Where(n => n.IsLeafNode()); } }
+
         public IList<NodeInfo> Nodes { get { return nodes; } }
     }
 }

GraphPad/Logic/NodeInfo.cs

         {
             return String.Format("Node {0}", Name);
         }
+
+        public bool IsRootNode()
+        {
+            return !Parents.Any();
+        }
+
+        public bool IsLeafNode()
+        {
+            return !Children.Any();
+        }
     }
 }