コード例 #1
0
        /// <summary>
        /// create a directed unit weighted graph with given dummySource to Patition 1 and Patition 2 to dummy sink.
        /// </summary>
        private static WeightedDiGraph <T, int> createFlowGraph(IGraph <T> graph,
                                                                T dummySource, T dummySink,
                                                                Dictionary <int, List <T> > partitions)
        {
            var workGraph = new WeightedDiGraph <T, int>();

            workGraph.AddVertex(dummySource);

            foreach (var group1Vertex in partitions[1])
            {
                workGraph.AddVertex(group1Vertex);
                workGraph.AddEdge(dummySource, group1Vertex, 1);
            }

            workGraph.AddVertex(dummySink);

            foreach (var group2Vertex in partitions[2])
            {
                workGraph.AddVertex(group2Vertex);
                workGraph.AddEdge(group2Vertex, dummySink, 1);
            }

            //now add directed edges from group 1 vertices to group 2 vertices
            foreach (var group1Vertex in partitions[1])
            {
                foreach (var edge in graph.GetVertex(group1Vertex).Edges)
                {
                    workGraph.AddEdge(group1Vertex, edge.TargetVertexKey, 1);
                }
            }

            return(workGraph);
        }
コード例 #2
0
        public void TravellingSalesman_Smoke_Test()
        {
            var graph = new WeightedDiGraph <int, int>();

            graph.AddVertex(0);
            graph.AddVertex(1);
            graph.AddVertex(2);
            graph.AddVertex(3);

            graph.AddEdge(0, 1, 1);
            graph.AddEdge(0, 2, 15);
            graph.AddEdge(0, 3, 6);

            graph.AddEdge(1, 0, 2);
            graph.AddEdge(1, 2, 7);
            graph.AddEdge(1, 3, 3);

            graph.AddEdge(2, 0, 9);
            graph.AddEdge(2, 1, 6);
            graph.AddEdge(2, 3, 12);

            graph.AddEdge(3, 0, 10);
            graph.AddEdge(3, 1, 4);
            graph.AddEdge(3, 2, 8);

            Assert.AreEqual(21, TravellingSalesman.GetMinWeight(graph));
        }
コード例 #3
0
        public void WeightedDiGraph_Smoke_Test()
        {
            var graph = new WeightedDiGraph <int, int>();

            graph.AddVertex(1);
            graph.AddVertex(2);
            graph.AddVertex(3);
            graph.AddVertex(4);
            graph.AddVertex(5);

            graph.AddEdge(1, 2, 1);
            graph.AddEdge(2, 3, 2);
            graph.AddEdge(3, 4, 3);
            graph.AddEdge(4, 5, 1);
            graph.AddEdge(4, 1, 6);
            graph.AddEdge(3, 5, 4);

            Assert.AreEqual(2, graph.GetAllOutEdges(4).Count);
            Assert.AreEqual(2, graph.GetAllInEdges(5).Count);

            Assert.AreEqual(5, graph.VerticesCount);

            Assert.IsTrue(graph.HasEdge(1, 2));

            graph.RemoveEdge(1, 2);

            Assert.IsFalse(graph.HasEdge(1, 2));

            graph.RemoveEdge(2, 3);
            graph.RemoveEdge(3, 4);
            graph.RemoveEdge(4, 5);
            graph.RemoveEdge(4, 1);

            Assert.IsTrue(graph.HasEdge(3, 5));
            graph.RemoveEdge(3, 5);
            Assert.IsFalse(graph.HasEdge(3, 5));

            graph.RemoveVertex(1);
            graph.RemoveVertex(2);
            graph.RemoveVertex(3);
            graph.RemoveVertex(4);

            graph.AddEdge(5, 5, 5);
            graph.RemoveEdge(5, 5);
            graph.RemoveVertex(5);

            Assert.AreEqual(0, graph.VerticesCount);
        }
コード例 #4
0
        /// <summary>
        /// clones this graph and creates a residual graph
        /// </summary>
        /// <param name="graph"></param>
        /// <returns></returns>
        private WeightedDiGraph <T, W> createResidualGraph(WeightedDiGraph <T, W> graph)
        {
            var newGraph = new WeightedDiGraph <T, W>();

            //clone graph vertices
            foreach (var vertex in graph.Vertices)
            {
                newGraph.AddVertex(vertex.Key);
            }

            //clone edges
            foreach (var vertex in graph.Vertices)
            {
                //Use either OutEdges or InEdges for cloning
                //here we use OutEdges
                foreach (var edge in vertex.Value.OutEdges)
                {
                    //original edge
                    newGraph.AddEdge(vertex.Key, edge.Key.Value, edge.Value);
                    //add a backward edge for residual graph with edge value as default(W)
                    newGraph.AddEdge(edge.Key.Value, vertex.Key, default(W));
                }
            }

            return(newGraph);
        }
コード例 #5
0
        /// <summary>
        /// Clones this graph and creates a residual graph.
        /// </summary>
        private WeightedDiGraph <T, W> createResidualGraph(IDiGraph <T> graph)
        {
            var newGraph = new WeightedDiGraph <T, W>();

            //clone graph vertices
            foreach (var vertex in graph.VerticesAsEnumberable)
            {
                newGraph.AddVertex(vertex.Key);
            }

            //clone edges
            foreach (var vertex in graph.VerticesAsEnumberable)
            {
                //Use either OutEdges or InEdges for cloning
                //here we use OutEdges
                foreach (var edge in vertex.OutEdges)
                {
                    //original edge
                    newGraph.AddOrUpdateEdge(vertex.Key, edge.TargetVertex.Key, edge.Weight <W>(), @operator);
                    //add a backward edge for residual graph with edge value as default(W)
                    newGraph.AddOrUpdateEdge(edge.TargetVertex.Key, vertex.Key, @operator.defaultWeight, @operator);
                }
            }

            return(newGraph);
        }
コード例 #6
0
        public void MinCut_Smoke_Test_2()
        {
            var graph = new WeightedDiGraph <char, int>();

            graph.AddVertex('A');
            graph.AddVertex('B');
            graph.AddVertex('C');
            graph.AddVertex('D');
            graph.AddVertex('E');
            graph.AddVertex('F');
            graph.AddVertex('G');
            graph.AddVertex('H');
            graph.AddVertex('I');
            graph.AddVertex('J');


            graph.AddEdge('A', 'B', 1);
            graph.AddEdge('A', 'C', 1);
            graph.AddEdge('A', 'D', 1);

            graph.AddEdge('B', 'E', 1);
            graph.AddEdge('C', 'E', 1);
            graph.AddEdge('D', 'E', 1);

            graph.AddEdge('E', 'F', 1);

            graph.AddEdge('F', 'G', 1);
            graph.AddEdge('F', 'H', 1);
            graph.AddEdge('F', 'I', 1);

            graph.AddEdge('G', 'J', 1);
            graph.AddEdge('H', 'J', 1);
            graph.AddEdge('I', 'J', 1);


            var algorithm = new MinCut <char, int>(new EdmondKarpOperators());

            var result = algorithm.ComputeMinCut(graph, 'A', 'J');

            Assert.AreEqual(result.Count, 1);
        }
コード例 #7
0
        public void EdmondKarp_Smoke_Test()
        {
            var graph = new WeightedDiGraph <char, int>();

            graph.AddVertex('S');
            graph.AddVertex('A');
            graph.AddVertex('B');
            graph.AddVertex('C');
            graph.AddVertex('D');
            graph.AddVertex('T');

            graph.AddEdge('S', 'A', 10);
            graph.AddEdge('S', 'C', 10);

            graph.AddEdge('A', 'B', 4);
            graph.AddEdge('A', 'C', 2);
            graph.AddEdge('A', 'D', 8);

            graph.AddEdge('B', 'T', 10);

            graph.AddEdge('C', 'D', 9);

            graph.AddEdge('D', 'B', 6);
            graph.AddEdge('D', 'T', 10);

            var algo = new EdmondKarpMaxFlow <char, int>(new EdmondKarpOperators());

            var result = algo.ComputeMaxFlow(graph, 'S', 'T');

            Assert.AreEqual(result, 19);
        }
コード例 #8
0
        public void MinCut_Smoke_Test_1()
        {
            var graph = new WeightedDiGraph <char, int>();

            graph.AddVertex('S');
            graph.AddVertex('A');
            graph.AddVertex('B');
            graph.AddVertex('C');
            graph.AddVertex('D');
            graph.AddVertex('T');

            graph.AddEdge('S', 'A', 10);
            graph.AddEdge('S', 'C', 10);

            graph.AddEdge('A', 'B', 4);
            graph.AddEdge('A', 'C', 2);
            graph.AddEdge('A', 'D', 8);

            graph.AddEdge('B', 'T', 10);

            graph.AddEdge('C', 'D', 9);

            graph.AddEdge('D', 'B', 6);
            graph.AddEdge('D', 'T', 10);

            var algorithm = new MinCut <char, int>(new EdmondKarpOperators());

            var result = algorithm.ComputeMinCut(graph, 'S', 'T');

            Assert.AreEqual(result.Count, 2);
        }
コード例 #9
0
        public void FordFulkerson_Smoke_Test()
        {
            var graph = new WeightedDiGraph <char, int>();

            graph.AddVertex('S');
            graph.AddVertex('A');
            graph.AddVertex('B');
            graph.AddVertex('C');
            graph.AddVertex('D');
            graph.AddVertex('T');

            graph.AddEdge('S', 'A', 10);
            graph.AddEdge('S', 'C', 10);

            graph.AddEdge('A', 'B', 4);
            graph.AddEdge('A', 'C', 2);
            graph.AddEdge('A', 'D', 8);

            graph.AddEdge('B', 'T', 10);

            graph.AddEdge('C', 'D', 9);

            graph.AddEdge('D', 'B', 6);
            graph.AddEdge('D', 'T', 10);

            var algorithm = new FordFulkersonMaxFlow <char, int>(new FordFulkersonOperators());

            var result = algorithm.ComputeMaxFlow(graph, 'S', 'T');

            Assert.AreEqual(result, 19);
        }
コード例 #10
0
        private WeightedDiGraph <T, W> clone(IDiGraph <T> graph)
        {
            var newGraph = new WeightedDiGraph <T, W>();

            foreach (var vertex in graph.VerticesAsEnumberable)
            {
                newGraph.AddVertex(vertex.Key);
            }

            foreach (var vertex in graph.VerticesAsEnumberable)
            {
                foreach (var edge in vertex.OutEdges)
                {
                    newGraph.AddEdge(vertex.Key, edge.TargetVertexKey, edge.Weight <W>());
                }
            }

            return(newGraph);
        }
コード例 #11
0
        public void Johnsons_Smoke_Test()
        {
            var graph = new WeightedDiGraph <char, int>();

            graph.AddVertex('S');
            graph.AddVertex('A');
            graph.AddVertex('B');
            graph.AddVertex('C');
            graph.AddVertex('D');
            graph.AddVertex('T');

            graph.AddEdge('S', 'A', -5);
            graph.AddEdge('S', 'C', 10);

            graph.AddEdge('A', 'B', 10);
            graph.AddEdge('A', 'C', 1);
            graph.AddEdge('A', 'D', 8);

            graph.AddEdge('B', 'T', 4);

            graph.AddEdge('C', 'D', 1);

            graph.AddEdge('D', 'B', 1);
            graph.AddEdge('D', 'T', 10);

            var algo = new JohnsonsShortestPath <char, int>(new JohnsonsShortestPathOperators());

            var result = algo.GetAllPairShortestPaths(graph);

            var testCase = result.First(x => x.Source == 'S' && x.Destination == 'T');

            Assert.AreEqual(2, testCase.Distance);

            var expectedPath = new char[] { 'S', 'A', 'C', 'D', 'B', 'T' };

            for (int i = 0; i < expectedPath.Length; i++)
            {
                Assert.AreEqual(expectedPath[i], testCase.Path[i]);
            }
        }
コード例 #12
0
        public void Dijikstra_Smoke_Test()
        {
            var graph = new WeightedDiGraph <char, int>();

            graph.AddVertex('S');
            graph.AddVertex('A');
            graph.AddVertex('B');
            graph.AddVertex('C');
            graph.AddVertex('D');
            graph.AddVertex('T');

            graph.AddEdge('S', 'A', 8);
            graph.AddEdge('A', 'S', 2);
            graph.AddEdge('S', 'C', 10);

            graph.AddEdge('A', 'B', 10);
            graph.AddEdge('A', 'C', 1);
            graph.AddEdge('A', 'D', 8);

            graph.AddEdge('B', 'T', 4);

            graph.AddEdge('C', 'D', 1);

            graph.AddEdge('D', 'B', 1);
            graph.AddEdge('D', 'T', 10);

            var algorithm = new DijikstraShortestPath <char, int>(new DijikstraShortestPathOperators());

            var result = algorithm.FindShortestPath(graph, 'S', 'T');

            Assert.AreEqual(15, result.Length);

            var expectedPath = new char[] { 'S', 'A', 'C', 'D', 'B', 'T' };

            for (int i = 0; i < expectedPath.Length; i++)
            {
                Assert.AreEqual(expectedPath[i], result.Path[i]);
            }
        }
コード例 #13
0
        public void BellmanFord_Smoke_Test()
        {
            var graph = new WeightedDiGraph <char, int>();

            graph.AddVertex('S');
            graph.AddVertex('A');
            graph.AddVertex('B');
            graph.AddVertex('C');
            graph.AddVertex('D');
            graph.AddVertex('T');

            graph.AddEdge('S', 'A', -10);
            graph.AddEdge('S', 'C', -5);

            graph.AddEdge('A', 'B', 4);
            graph.AddEdge('A', 'C', 2);
            graph.AddEdge('A', 'D', 8);

            graph.AddEdge('B', 'T', 10);

            graph.AddEdge('C', 'D', 9);

            graph.AddEdge('D', 'B', 6);
            graph.AddEdge('D', 'T', 10);

            var algo = new BellmanFordShortestPath <char, int>(new BellmanFordShortestPathOperators());

            var result = algo.GetShortestPath(graph, 'S', 'T');

            Assert.AreEqual(4, result.Length);

            var expectedPath = new char[] { 'S', 'A', 'B', 'T' };

            for (int i = 0; i < expectedPath.Length; i++)
            {
                Assert.AreEqual(expectedPath[i], result.Path[i]);
            }
        }
コード例 #14
0
        /// <summary>
        /// getting the path from a source vertex to a target vertex
        /// </summary>
        /// <param name="source">inital vertex to start from</param>
        /// <param name="target"> target vertex</param>
        /// <param name="categoryName">choose from: NBA,Politicans,GeneralKnowledge,Movies,Music,Celeb</param>
        /// <returns></returns>
        //הרצה של הדיקסטרה פעם אחת בלבד
        public List <List <string> > GetPath(string source, string target, string categoryName)
        {
            //get all vertecies and edges from db
            DBservices db = new DBservices();

            switch (categoryName.ToUpper())
            {
            case "GENERAL KNOWLEDGE":
                categoryName = "General";
                break;

            case "FILMS":
                categoryName = "Movies";
                break;

            case "CELEBRITY":
                categoryName = "Celeb";
                break;

            case "POLITICS":
                categoryName = "Politicians";
                break;

            default:
                break;
            }

            List <List <string> > TwoPaths = new List <List <string> >();
            string edgeTableName           = categoryName + "Edges";
            string verteciesTableName      = categoryName + "Vertecies";

            //פה נשמור את הדרך שלנו
            List <string> path = new List <string>();


            //קריאה מדאתא בייס על ידי הקטגוריה שקיבלנו מהמשתמש
            //get edges and vertecies for the given category
            List <string>         vertecies = new List <string>();
            List <List <string> > edges     = new List <List <string> >();

            if (HttpContext.Current.Application[verteciesTableName] != null)
            {
                vertecies = HttpContext.Current.Application[verteciesTableName] as List <string>;
            }
            else
            {
                vertecies = db.GetAllVertecies("DBConnectionString", verteciesTableName);
            }
            if (HttpContext.Current.Application[edgeTableName] != null)
            {
                edges = HttpContext.Current.Application[edgeTableName] as List <List <string> >;
            }
            else
            {
                edges = db.GetEdges("DBConnectionString", edgeTableName);
            }
            //create a graph
            var graph = new WeightedDiGraph <string, int>();

            //insert vertecies to the graph
            foreach (string vertex in vertecies)
            {
                graph.AddVertex(vertex);
            }
            //insert edges to the graph
            foreach (var edge in edges)
            {
                graph.AddEdge(edge[0], edge[1], 1);
            }
            //create dijkstra algorithm
            var algorithm = new DijikstraShortestPath <string, int>(new DijikstraShortestPathOperators());

            List <string> pathsTwo = new List <string>();

            try
            {
                var result = algorithm.FindShortestPath(graph, source, target);
                if (result.Path.Count == 1)
                {
                    pathsTwo.Add(source);
                    pathsTwo.Add(target);
                    TwoPaths.Add(pathsTwo);
                }

                else
                {
                    TwoPaths.Add(result.Path);
                }
                TwoPaths.Add(getThreeMoreRandom(source, categoryName));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                // TwoPaths.Add(getThreeMoreRandom(source, categoryName));
                return(TwoPaths);
            }
            return(TwoPaths);
        }
コード例 #15
0
        /// <summary>
        ///getting a list of random paths for testing
        /// </summary>
        /// <param name="Paths">empty list of paths to fill</param>
        /// <returns></returns>
        ///         ---NOT IN USE---
        public List <int> GetPathsSimple_OLD(ref List <List <string> > Paths)
        {
            List <string>         vertecies = new List <string>();
            List <List <string> > edges     = new List <List <string> >();

            // get all vertecies and edges from DB
            DBservices db = new DBservices();

            vertecies = db.GetAllVertecies("TheMoleConnection", "PoliticiansVertecies");
            edges     = db.GetEdges("TheMoleConnection", "PoliticiansEdges");

            //1. create a graph
            var graph = new WeightedDiGraph <string, int>();

            //2. insert vertecies to the graph
            foreach (string vertex in vertecies)
            {
                graph.AddVertex(vertex);
            }
            //3. insert edges to the graph
            foreach (var edge in edges)
            {
                graph.AddEdge(edge[0], edge[1], 1);
            }

            //4. create dijkstra algorithm
            var algorithm = new DijikstraShortestPath <string, int>(new DijikstraShortestPathOperators());


            List <int> pathsCount = new List <int>();

            //var result = algorithm.FindShortestPath(graph, Source, Target);
            //pathsCount.Add(result.Path.Count);
            //Paths.Add(result.Path

            //5.run the algoritm for 110 random vertecies.
            for (int i = 0; i < 200; i++)
            {
                int sourceVertex = random.Next(0, vertecies.Count);
                int targetVertex = random.Next(0, vertecies.Count);
                //if source and target pages are the same DON'T run the algorithm
                if (sourceVertex != targetVertex)
                {
                    List <string> pathsTwo = new List <string>();
                    var           result   = algorithm.FindShortestPath(graph, vertecies[sourceVertex], vertecies[targetVertex]);
                    pathsCount.Add(result.Path.Count);
                    if (result.Path.Count == 1)
                    {
                        pathsTwo.Add(vertecies[sourceVertex]);
                        pathsTwo.Add(vertecies[targetVertex]);
                        Paths.Add(pathsTwo);
                    }
                    else
                    {
                        Paths.Add(result.Path);
                    }
                }
            }

            return(pathsCount);
        }
コード例 #16
0
        public void AStar_Smoke_Test()
        {
            var testLocations = @"A5 30 573
                            A4 30 483
                            A2 30 178
                            A1 30 48
                            B1 207 48
                            B2 207 161
                            B3 144 339
                            B4 129 443
                            B5 127 479
                            C2 258 162
                            C3 240 288
                            C4 225 443
                            C5 336 573
                            D1 438 48
                            D2 438 174
                            D3 438 335
                            D4 438 473
                            D5 438 573
                            E4 575 475
                            E5 684 493
                            F1 611 48
                            F2 600 173
                            F5 701 573
                            G1 797 48
                            G2 797 150
                            G2b 770 151
                            G4 797 382
                            G4b 770 382
                            G5 797 573";

            var locationMappings = new Dictionary <string, Location>();

            var graph = new WeightedDiGraph <Location, double>();

            using (var reader = new StringReader(testLocations))
            {
                string line;
                while ((line = reader.ReadLine()?.Trim()) != null)
                {
                    var @params = line.Split(' ');

                    var location = new Location()
                    {
                        Point = new Point(double.Parse(@params[1]), double.Parse(@params[2])),
                        Name  = @params[0]
                    };

                    locationMappings.Add(@params[0], location);
                    graph.AddVertex(location);
                }
            }

            var testConnections = @"A1 2 B1 A2
                                A2 3 A1 B2 A4
                                A4 3 A2 B5 A5
                                A5 2 A4 C5
                                B1 3 A1 D1 B2
                                B2 4 C2 C3 A2 B1
                                B3 1 B4
                                B4 3 B3 B5 C4
                                B5 3 A4 C5 B4
                                C2 3 D2 B2 C3
                                C3 3 C2 B2 C4
                                C4 3 B4 C3 D4
                                C5 3 D5 B5 A5
                                D1 3 B1 F1 D2
                                D2 3 C2 D1 F2
                                D3 1 D4
                                D4 4 D3 C4 E4 D5
                                D5 3 C5 D4 F5
                                E4 3 D4 E5 F2
                                F1 3 F2 D1 G1
                                F2 4 F1 D2 G2b E4
                                F5 3 E5 G5 D5
                                G1 2 G2 F1
                                G2 3 G1 G2b G4
                                G2b 3 G2 F2 G4b
                                G4 3 G4b G2 G5
                                G4b 3 G4 G2b E5
                                G5 2 F5 G4
                                E5 3 F5 E4 G4b";

            using (var reader = new StringReader(testConnections))
            {
                string line;
                while ((line = reader.ReadLine()?.Trim()) != null)
                {
                    var @params = line.Split(' ');

                    for (int i = 2; i < int.Parse(@params[1]) + 2; i++)
                    {
                        graph.AddEdge(locationMappings[@params[0]], locationMappings[@params[i]],
                                      EucledianDistanceCalculator.GetEucledianDistance(locationMappings[@params[0]].Point,
                                                                                       locationMappings[@params[i]].Point));
                    }
                }
            }

            var algorithm = new AStarShortestPath <Location, double>(new AStarShortestPathOperators(), new AStarSearchHeuristic());

            var result = algorithm.FindShortestPath(graph, locationMappings["A1"], locationMappings["G5"]);

            Assert.AreEqual(10, result.Path.Count);
            Assert.AreEqual(1217.3209396395309, result.Length);

            var expectedPath = new string[] { "A1", "B1", "B2", "C3", "C4", "D4", "E4", "E5", "F5", "G5" };

            for (int i = 0; i < expectedPath.Length; i++)
            {
                Assert.AreEqual(expectedPath[i], result.Path[i].Name);
            }
        }
コード例 #17
0
        /// <summary>
        /// getting the path from a source vertex to a target vertex
        /// </summary>
        /// <param name="source">inital vertex to start from</param>
        /// <param name="traget"> target vertex</param>
        /// <param name="categoryName">choose from: NBA,Politicans,GeneralKnowledge,Movies,Music,Celeb</param>
        /// <returns></returns>
        public List <List <string> > GetPath(string source, string target, string categoryName)
        {
            //get all vertecies and edges from db
            DBservices db = new DBservices();

            List <List <string> > TwoPaths = new List <List <string> >();
            string edgeCategoryName        = "";
            string verteciesCategoryName   = "";

            switch (categoryName.ToUpper())
            {
            case "NBA":
                edgeCategoryName      = "NBAEdges";
                verteciesCategoryName = "NBAVertecies";
                break;

            case "GENERAL KNOWLEDGE":
                edgeCategoryName      = "GeneralEdges";
                verteciesCategoryName = "GeneralVertecies";
                break;

            case "FILMS":
                edgeCategoryName      = "MoviesEdges";
                verteciesCategoryName = "MoviesVertecies";
                break;

            case "MUSIC":
                edgeCategoryName      = "MusicEdges";
                verteciesCategoryName = "MusicVertecies";
                break;

            case "CELEBRITY":
                edgeCategoryName      = "CelebEdges";
                verteciesCategoryName = "CelebVertecies";
                break;

            case "POLITICS":
                edgeCategoryName      = "PoliticiansEdges";
                verteciesCategoryName = "PoliticiansVertecies";
                break;

            default:
                break;
            }
            List <string> path = new List <string>();


            //get edges and vertecies for the given category
            List <string>         vertecies = new List <string>();
            List <List <string> > edges     = new List <List <string> >();

            if (HttpContext.Current.Application[verteciesCategoryName] != null)
            {
                vertecies = HttpContext.Current.Application[verteciesCategoryName] as List <string>;
            }
            else
            {
                vertecies = db.GetAllVertecies("TheMoleConnection", verteciesCategoryName);
            }
            if (HttpContext.Current.Application[edgeCategoryName] != null)
            {
                edges = HttpContext.Current.Application[edgeCategoryName] as List <List <string> >;
            }
            else
            {
                edges = db.GetEdges("TheMoleConnection", edgeCategoryName);
            }
            //create a graph
            var graph = new WeightedDiGraph <string, int>();

            //insert vertecies to the graph
            foreach (string vertex in vertecies)
            {
                graph.AddVertex(vertex);
            }
            //insert edges to the graph
            foreach (var edge in edges)
            {
                graph.AddEdge(edge[0], edge[1], 1);
            }
            //create dijkstra algorithm
            var algorithm = new DijikstraShortestPath <string, int>(new DijikstraShortestPathOperators());

            List <string> pathsTwo = new List <string>();

            try
            {
                var result = algorithm.FindShortestPath(graph, source, target);
                if (result.Path.Count == 1)
                {
                    pathsTwo.Add(source);
                    pathsTwo.Add(target);
                    TwoPaths.Add(pathsTwo);
                }

                else
                {
                    TwoPaths.Add(result.Path);
                }
                TwoPaths.Add(getThreeMoreRandom(source, categoryName));
            }
            catch (Exception ex)
            {
                // TwoPaths.Add(getThreeMoreRandom(source, categoryName));
                return(TwoPaths);
            }
            return(TwoPaths);
        }
コード例 #18
0
        public List <List <string> > StartAGame(string categoryName)
        {
            List <List <string> > StartVerteciesAndPaths = new List <List <string> >();
            string edgeCategoryName      = "";
            string verteciesCategoryName = "";

            switch (categoryName.ToUpper())
            {
            case "NBA":
                edgeCategoryName      = "NBAEdges";
                verteciesCategoryName = "NBAVertecies";
                break;

            case "GENERAL KNOWLEDGE":
                edgeCategoryName      = "GeneralEdges";
                verteciesCategoryName = "GeneralVertecies";
                break;

            case "FILMS":
                edgeCategoryName      = "MoviesEdges";
                verteciesCategoryName = "MoviesVertecies";
                break;

            case "MUSIC":
                edgeCategoryName      = "MusicEdges";
                verteciesCategoryName = "MusicVertecies";
                break;

            case "CELEBRITY":
                edgeCategoryName      = "CelebEdges";
                verteciesCategoryName = "CelebVertecies";
                break;

            case "POLITICS":
                edgeCategoryName      = "PoliticiansEdges";
                verteciesCategoryName = "PoliticiansVertecies";
                break;

            default:
                break;
            }
            DBservices db = new DBservices();
            //get edges and vertecies for the given category
            List <string>         vertecies = new List <string>();
            List <List <string> > edges     = new List <List <string> >();

            if (HttpContext.Current.Application[verteciesCategoryName] != null)
            {
                vertecies = HttpContext.Current.Application[verteciesCategoryName] as List <string>;
            }
            else
            {
                vertecies = db.GetAllVertecies("TheMoleConnection", verteciesCategoryName);
            }
            if (HttpContext.Current.Application[edgeCategoryName] != null)
            {
                edges = HttpContext.Current.Application[edgeCategoryName] as List <List <string> >;
            }
            else
            {
                edges = db.GetEdges("TheMoleConnection", edgeCategoryName);
            }
            //create a graph
            var graph = new WeightedDiGraph <string, int>();

            //insert vertecies to the graph
            foreach (string vertex in vertecies)
            {
                graph.AddVertex(vertex);
            }
            //insert edges to the graph
            foreach (var edge in edges)
            {
                graph.AddEdge(edge[0], edge[1], 1);
            }
            //create dijkstra algorithm
            var  algorithm = new DijikstraShortestPath <string, int>(new DijikstraShortestPathOperators());
            bool isDone    = false;

            while (!isDone)
            {
                int sourceVertex = random.Next(0, vertecies.Count);
                int targetVertex = random.Next(0, vertecies.Count);
                if (sourceVertex != targetVertex)
                {
                    List <string> pathsTwo = new List <string>();
                    var           result   = algorithm.FindShortestPath(graph, vertecies[sourceVertex], vertecies[targetVertex]);
                    var           result1  = algorithm.FindShortestPath(graph, vertecies[targetVertex], vertecies[sourceVertex]);

                    if (result.Path.Count == result1.Path.Count)
                    {
                        isDone = true;
                        if (result.Path.Count == 1)
                        {
                            //pathsTwo.Add(vertecies[sourceVertex]);
                            //pathsTwo.Add(vertecies[targetVertex]);
                            //StartVerteciesAndPaths.Add(pathsTwo);
                            //pathsTwo.Clear();
                            //pathsTwo.Add(vertecies[targetVertex]);
                            //pathsTwo.Add(vertecies[sourceVertex]);
                            //StartVerteciesAndPaths.Add(pathsTwo);

                            isDone = false;
                        }
                        else
                        {
                            StartVerteciesAndPaths.Add(result.Path);
                            StartVerteciesAndPaths.Add(result1.Path);
                        }
                    }
                }
            }
            List <string> edgesForFirstVertex  = this.getThreeMoreRandom(StartVerteciesAndPaths[0][0], categoryName);
            List <string> edgesForSecondVertex = this.getThreeMoreRandom(StartVerteciesAndPaths[1][0], categoryName);

            StartVerteciesAndPaths.Add(edgesForFirstVertex);
            StartVerteciesAndPaths.Add(edgesForSecondVertex);

            return(StartVerteciesAndPaths);
        }
コード例 #19
0
        /// <summary>
        /// getting rendom paths of only two-direction vertecies for testing
        /// </summary>
        /// <param name="Paths">empty list of paths to fill</param>
        /// <returns></returns>
        public List <int> GetPathsAdvancedIntersect(ref List <List <string> > Paths)
        {
            List <string>         vertecies = new List <string>();
            List <List <string> > edges     = new List <List <string> >();

            // get all vertecies and edges from DB
            DBservices db = new DBservices();

            vertecies = db.GetAllVertecies("TheMoleConnection", "MoviesVertecies");
            edges     = db.GetEdges("TheMoleConnection", "MoviesEdges");

            //1. create a graph
            var graph = new WeightedDiGraph <string, int>();

            //2. insert vertecies to the graph
            foreach (string vertex in vertecies)
            {
                graph.AddVertex(vertex);
            }
            //3. insert edges to the graph
            foreach (var edge in edges)
            {
                graph.AddEdge(edge[0], edge[1], 1);
            }
            //remove one-direction edges
            List <List <string> > twoDirectionsEdges = new List <List <string> >();

            foreach (var edge in edges)
            {
                if (!graph.HasEdge(edge[1], edge[0]))
                {
                    graph.RemoveEdge(edge[0], edge[1]);
                }
                if (graph.HasEdge(edge[1], edge[0]))
                {
                    twoDirectionsEdges.Add(edge);
                }
            }
            //4. create dijkstra algorithm
            var algorithm = new DijikstraShortestPath <string, int>(new DijikstraShortestPathOperators());


            List <int> pathsCount = new List <int>();

            //var result = algorithm.FindShortestPath(graph, Source, Target);
            //pathsCount.Add(result.Path.Count);
            //Paths.Add(result.Path

            //5.run the algoritm for 110 random vertecies.
            for (int i = 0; i < 200; i++)
            {
                int sourceVertex = random.Next(0, vertecies.Count);
                int targetVertex = random.Next(0, vertecies.Count);
                //if source and target pages are the same DON'T run the algorithm
                if (sourceVertex != targetVertex)
                {
                    var result = algorithm.FindShortestPath(graph, vertecies[sourceVertex], vertecies[targetVertex]);
                    pathsCount.Add(result.Path.Count);
                    Paths.Add(result.Path);
                }
            }

            return(pathsCount);
        }
コード例 #20
0
        /// <summary>
        ///getting a list of random paths for testing
        /// </summary>
        /// <param name="Paths">empty list of paths to fill</param>
        /// <returns></returns>
        /// מחזיר הפניה לרשימה של כל הדרכים
        ///       ---NOT IN USE ??? ---
        public List <int> GetPathsSimple(ref List <List <string> > Paths, string categoryName)
        {
            //רשימת ערכים
            List <string> vertecies = new List <string>();
            //הקשתות - רשימה של רשימה
            List <List <string> > edges = new List <List <string> >();

            // get all vertecies and edges from DB
            DBservices db   = new DBservices();
            string     Vsrt = categoryName + "Vertecies";
            string     Estr = categoryName + "Edges";

            vertecies = db.GetAllVertecies("DBConnectionString", Vsrt);
            edges     = db.GetEdges("DBConnectionString", Estr);

            //הכרזה על גרף עם משקולת של 1 על כל קשת כדי להריץ את אלגוריתם הדיקסטרה
            //1. create a graph
            var graph = new WeightedDiGraph <string, int>();

            //הוספה לגרף את כל הצמתים שהבאנו מהדאתא בייס
            //2. insert vertecies to the graph
            foreach (string vertex in vertecies)
            {
                graph.AddVertex(vertex);
            }
            //הוספת כל הקשתות - מכיל ממי יצאתי, למי אני יוצא, ומשקל על הקשת 1
            //3. insert edges to the graph
            foreach (var edge in edges)
            {
                graph.AddEdge(edge[0], edge[1], 1);
            }
            //יצירת האלגוריתם הדיקסטרה באמצעות סיפריית
            //using Advanced.Algorithms.DataStructures.Graph.AdjacencyList;
            //using Advanced.Algorithms.Graph;
            //4. create dijkstra algorithm
            var algorithm = new DijikstraShortestPath <string, int>(new DijikstraShortestPathOperators());

            //רשימה אשר סופרת בכל הדרכים כמה ערכים ישלי
            //מכילה את התוצאות של הדיקסטרה
            List <int> pathsCount = new List <int>();

            //הרצת האלגוריתם על 200 דרכים כטסט לראות מה הדרכים הכי קצרות
            //5.run the algoritm for 110 random vertecies.
            for (int i = 0; i < 200; i++)
            {
                //קבלת ערך רנדומלי מהרשימה שייצאנו מהדאא בייס מאינדקס 0 ועד הסוף
                int sourceVertex = random.Next(0, vertecies.Count);
                int targetVertex = random.Next(0, vertecies.Count);

                //בדיקת מקרה קצה שהערכים שונים
                //אם שונה מפעיל את האלגוריתם דיקסטרה מלמעלה
                //if source and target pages are the same DON'T run the algorithm
                if (sourceVertex != targetVertex)
                {
                    List <string> pathsTwo = new List <string>();
                    var           result   = algorithm.FindShortestPath(graph, vertecies[sourceVertex], vertecies[targetVertex]);
                    //הוספת תכונה לרשימת הערכים בדרך מסויימת - כמה צעדים זה לקח
                    pathsCount.Add(result.Path.Count);
                    //מקרה קצה - אם אין ערך שמפריד בין ערך ההתחלה והסיום - בלי לעבור בשום ערך אחר בדרך
                    //נוסיף לליסט שיצרנו את ההערך התחלה וערך הסיום עם כמות צעדים של 1
                    if (result.Path.Count == 1)
                    {
                        pathsTwo.Add(vertecies[sourceVertex]);
                        pathsTwo.Add(vertecies[targetVertex]);
                        Paths.Add(pathsTwo);
                    }
                    //אחרת לא מדובר במקרה קצה ונכניס רגיל
                    else
                    {
                        Paths.Add(result.Path);
                    }
                }
            }

            return(pathsCount);
        }