예제 #1
0
        private static void CreateGraph(ref MyGraph<string> myGraph)
        {
            //Adds nodes to our graph
            Node<String> n1 = myGraph.AddNode("OREGON");
            Node<String> n2 = myGraph.AddNode("CALIFORNIA");
            Node<String> n3 = myGraph.AddNode("IDAHO");
            Node<String> n4 = myGraph.AddNode("UTAH");
            Node<String> n5 = myGraph.AddNode("NEW MEXICO");
            Node<String> n6 = myGraph.AddNode("KANSAS");
            Node<String> n7 = myGraph.AddNode("SOUTH DAKOTA");
            Node<String> n8 = myGraph.AddNode("NORTH DAKOTA");
            Node<String> n9 = myGraph.AddNode("IOWA");
            Node<String> n10 = myGraph.AddNode("TENNESSEE");
            Node<String> n11 = myGraph.AddNode("NEW YORK");
            Node<String> n12 = myGraph.AddNode("FLORIDA");
            Node<String> n13 = myGraph.AddNode("TEXAS");

            //Creates edges between the graphs nodes
            myGraph.AddEdge("OREGON", "CALIFORNIA");
            myGraph.AddEdge("CALIFORNIA", "UTAH");
            myGraph.AddEdge("UTAH", "IDAHO");
            myGraph.AddEdge("UTAH", "NEW MEXICO");
            myGraph.AddEdge("NEW MEXICO", "KANSAS");
            myGraph.AddEdge("NEW MEXICO", "TEXAS");
            myGraph.AddEdge("TEXAS", "TENNESSEE");
            myGraph.AddEdge("TEXAS", "FLORIDA");
            myGraph.AddEdge("TEXAS", "KANSAS");
            myGraph.AddEdge("KANSAS", "SOUTH DAKOTA");
            myGraph.AddEdge("SOUTH DAKOTA", "NORTH DAKOTA");
            myGraph.AddEdge("NORTH DAKOTA", "IOWA");
            myGraph.AddEdge("IOWA", "TENNESSEE");
            myGraph.AddEdge("TENNESSEE", "FLORIDA");
            myGraph.AddEdge("TENNESSEE", "NEW YORK");
        }
예제 #2
0
        public void Deserialize(string fileName, out MyGraph<Location> graph, out ArduinoGroupWrapper arduinoGroup)
        {
            var binder = new TypeNameSerializationBinder();
            var graphString = File.ReadAllText(fileName);
            var deserialized = JsonConvert.DeserializeObject<SerializeWrapper>(graphString, new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto,
                Binder = binder
            });

            graph = deserialized.Graph;
            arduinoGroup = deserialized.ArduinoGroup;

            foreach (var edge in graph.Edges.OfType<MyEdge<Location>>().ToList())
            {
                var from = edge.Source;
                var to = edge.Destination;

                var vertices = graph.SubGraphs.SelectMany(subgraph => subgraph.Vertices).ToList();
                vertices.AddRange(graph.Vertices);

                graph.RemoveEdge(edge);
                graph.AddEdge(
                    new MyEdge<Location>(vertices.First(vertex => vertex.Name == from.Name),
                    vertices.First(vertex => vertex.Name == to.Name),edge.DestinationArrow)
                );
            }
        }
예제 #3
0
        private static Node<string> BFSGetGoalParent(MyGraph<string> graph, Node<string> rootNode, Node<string> goalNode)
        {
            // Create a queue to keep track of search
            Queue<Node<String>> q = new Queue<Node<string>>();
            q.Enqueue(rootNode);
            rootNode.Visited = true;

            //Visiting children each level at a time
            while (!(q.Count == 0))
            {
                Node<string> n = q.Dequeue();
                Node<string> child = null;

                //Check each child before moving on to the next level
                while ((child = getUnvisitedChildNode(n)) != null)
                {
                    q.Enqueue(child);
                    child.Visited = true;
                    if (child == goalNode)
                    {
                        clearNodes(graph);
                        return n;
                    }
                }
            }
            return null;
        }
예제 #4
0
        internal static List<Node<String>> BFS(MyGraph<string> graph, string root, string goal)
        {
            //Find the nodes
            Node<string> rootNode = graph.NodeSet.Find(n => n.Data == root);
            Node<string> goalNode = graph.NodeSet.Find(n => n.Data == goal);

            if (rootNode == null || goalNode == null)
            {
                throw new ArgumentException("The start or goal element is not part of the graph.");
            }

            //List to keep track of path
            List<Node<string>> route = new List<Node<string>>();

            Node<string> temp = goalNode;

            //Loop through route by getting each nodes parent, until rootnode is reached
            while (temp != rootNode)
            {
                route.Add(temp);
                temp = BFSGetGoalParent(graph, rootNode, temp);
            }

            route.Add(rootNode);
            return route;
        }
예제 #5
0
 private static void TestMyGraph()
 {
     var foo = new MyGraph<int>();
     foo.Add(1);
     foo.Add(2);
     foo.Add(3);
     foreach(var item in foo.Get())
     {
         Console.WriteLine(item);
     }
 }
예제 #6
0
        public void Persist(MyGraph<Location> graph, ArduinoGroupWrapper arduinoGroup, string fileName)
        {
            var binder = new TypeNameSerializationBinder();
            var serilaizeWrapper = new SerializeWrapper(graph, arduinoGroup);

            var serializedJson = JsonConvert.SerializeObject(serilaizeWrapper, Formatting.Indented, new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.Auto,
                    Binder = binder
                });

            File.WriteAllText(fileName, serializedJson);
        }
예제 #7
0
        static void Main(string[] args)
        {
            //Instance of our graph
            MyGraph<string> myGraph = new MyGraph<string>();

            //Create the graph
            CreateGraph(ref myGraph);

            //Find a route from Idaho to South Dakota - DFS
            Console.WriteLine("Finding a route from Idaho to South Dakota - DFS:");

            try
            {
                Stack<Node<string>> route = GraphTraversal.DFS(myGraph, "IDAHO", "SOUTH DAKOTA");

                foreach (var city in route.Reverse())
                {
                    Console.WriteLine("{0}", city.Data.ToString());
                }
            }
            catch (ArgumentException e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine();

            //Find a route from Idaho to South Dakota - BFS
            Console.WriteLine("Finding a route from Idaho to South Dakota - BFS:");

            try
            {
                List<Node<string>> route = GraphTraversal.BFS(myGraph, "IDAHO", "SOUTH DAKOTA");

                foreach (var city in route.Reverse<Node<string>>())
                {
                    Console.WriteLine("{0}", city.Data.ToString());
                }
            }
            catch (ArgumentException e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadLine();
        }
예제 #8
0
        // DFS and BFS methods strongly inspired by: http://www.codeproject.com/Articles/32212/Introduction-to-Graph-with-Breadth-First-Search-BF
        internal static Stack<Node<String>> DFS(MyGraph<string> graph, string root, string goal)
        {
            //Find the nodes
            Node<string> rootNode = graph.NodeSet.Find(n => n.Data == root);
            Node<string> goalNode = graph.NodeSet.Find(n => n.Data == goal);

            if (rootNode == null || goalNode == null)
            {
                throw new ArgumentException("The start or goal element is not part of the graph.");
            }

            // Create a stack to keep track of search
            Stack<Node<string>> route = new Stack<Node<string>>();
            //Add rootNode to the bottom of the stack and mark it as visited
            route.Push(rootNode);
            rootNode.Visited = true;

            // Keep getting new nodes until stack is empty - or a route is found
            while (!(route.Count == 0))
            {
                Node<string> n = route.Peek();
                Node<string> child = getUnvisitedChildNode(n);
                if (child != null)
                {
                    route.Push(child);
                    child.Visited = true;
                    if (child == goalNode)
                    {
                        clearNodes(graph);
                        return route;
                    }

                }
                else
                    route.Pop();

            }
            return null;
        }
예제 #9
0
        public void GenerateFiles(MyGraph<Location> graph, ArduinoGroupWrapper arduinoGroup, string foldername)
        {
            CreateSegments(graph);

            if (!Directory.Exists(foldername))
            {
                Directory.CreateDirectory(foldername);
            }

            CopyServerFolder(foldername);

            CreateArduinos(graph, arduinoGroup);

            foreach (var arduino in _arduinos)
            {
                CopyArduinoFolder(arduino, foldername);
            }

            var readme = new Readme(_segmentManager, _arduinos);
            var readmeContent = readme.TransformText();
            File.WriteAllText(Path.Combine(foldername, "readme.txt"), readmeContent);
        }
예제 #10
0
 public SerializeWrapper(MyGraph<Location> graph, ArduinoGroupWrapper arduinoGroup)
 {
     Graph = graph;
     ArduinoGroup = arduinoGroup;
 }
예제 #11
0
 private static void clearNodes(MyGraph<string> graph)
 {
     foreach (var node in graph.NodeSet)
     {
         node.Visited = false;
     }
 }
예제 #12
0
        private void CreateSegments(MyGraph<Location> graph)
        {
            _segmentManager = new SegmentManager();

            foreach (var edge in graph.Edges.OfType<MyEdge<Location>>())
            {
                var segment = _segmentManager.Segments.FirstOrDefault(sgmt =>
                                                       sgmt.Switches.Any(switchItem => switchItem.Name == edge.Source.Name)
                                                       || sgmt.Lights.Any(lightItem => lightItem.Name == edge.Destination.Name));
                if (segment != null)
                {
                    if (segment.Switches.All(switchItem => switchItem.Name != edge.Source.Name))
                    {
                        segment.AddSwitch(edge.Source.Name, _identity.NextAddress());
                    }

                    if (segment.Lights.All(lightItem => lightItem.Name != edge.Destination.Name))
                    {
                        segment.AddLight(edge.Destination.Name, _identity.NextAddress());
                    }
                }
                else
                {
                    segment = new Segment(_identity.NextSegmentName(), _identity.NextSequentialId());
                    _segmentManager.AddSegmentItem(segment);
                    segment.AddSwitch(edge.Source.Name, _identity.NextAddress());
                    segment.AddLight(edge.Destination.Name, _identity.NextAddress());
                }
            }
        }
예제 #13
0
        private void CreateArduinos(MyGraph<Location> graph, ArduinoGroupWrapper arduinoGroup)
        {
            var groupSegment = new Dictionary<string, List<Segment>>();
            _arduinos = new List<Arduino>();

            foreach (var segment in _segmentManager.Segments)
            {
                var buildBlock = segment.Switches.First();
                var locationName =
                    graph.SubGraphs.First(subGraph => subGraph.Vertices.Any(vertex => vertex.Name == buildBlock.Name)).Label;

                var agroup =
                    arduinoGroup.ArduinoGroups.FirstOrDefault(
                        group => group.Locations.Any(location => location == locationName));
                if (agroup != null)
                {
                    if (!groupSegment.ContainsKey(agroup.Name))
                    {
                        groupSegment[agroup.Name] = new List<Segment>();
                    }
                    groupSegment[agroup.Name].Add(segment);
                }
                else
                {
                    if (!groupSegment.ContainsKey(locationName))
                    {
                        groupSegment[locationName] = new List<Segment>();
                    }

                    groupSegment[locationName].Add(segment);
                }
            }

            foreach (var groupSegmentItem in groupSegment)
            {
                var arduinos = new List<Arduino>();
                foreach (var segment in groupSegmentItem.Value)
                {
                    var currentArduino = new Arduino(groupSegmentItem.Key);

                    var segment1 = segment;
                    CreateArduinoSwitches(segment1.Switches, ref currentArduino, arduinos);
                    CreateArduinoRelay(segment1.Lights, ref currentArduino, arduinos);
                    arduinos.Add(currentArduino);
                }
                _arduinos.AddRange(ZipArduinos(arduinos));
            }

            MakeArduinoNameUnique();
        }
예제 #14
0
        static void RecursiveSearch(int v, ref List <int> clique, ref List <int> neighbours, MyGraph g)
        {
            //Получить соседей для вершины
            List <int> candidates = g.GetNeighbors(v);

            //Добавим саму вершину в список соседей
            candidates.Add(v);
            //Получить пересечение со списком всех вершин-соседей в клике - это общий список соседей клики при добавлении этой вершины
            candidates = candidates.Intersect(neighbours).ToList <int>();
            clique.Add(v);
            //Получить список вершин из общего списка соседей клики, которые еще не были добавлены в клику
            List <int> cut_n = candidates.Except(clique).ToList <int>();

            //Если есть еще нерассмотренные вершины из общего списка соседей клики
            if (cut_n.Count() != 0)
            {
                //Найдем вершину, максимально связанную с прочими нерассмотренными вершинами
                int node = GetNodeToAdd(g, cut_n, clique);
                if (node.Equals(-1))
                {
                    return;
                }
                RecursiveSearch(node, ref clique, ref candidates, g);
                if (globalClick.Count() < clique.Count())
                {
                    globalClick.Clear();
                    globalClick.AddRange(clique);
                }
            }
            else
            {
                return;
            }
        }
예제 #15
0
        public void MyGraphSecondNodeConnections_Contains_MyGraphFirstNode()
        {
            MyGraph <GraphNodeTestClass> myGraph = ArrangeAndConnectMyGraphNodes();

            Assert.Contains(myGraph[0], myGraph[1].Connections);
        }