/// <summary> /// The create report. /// </summary> /// <param name="graph"> /// The graph. /// </param> public void CreateReport(Graph graph) { foreach (var node in graph.Neighborhood) { foreach (var subnode in node.Value.Neighbours) { // InDegree if (subnode.Status != NodeStatus.Invalid) { ++graph.Neighborhood[subnode.Uri].InDegree; } // OutDegree ++graph.Neighborhood[node.Key].OutDegree; } } var floyd = new FloydWarshall(); var sw = new Stopwatch(); sw.Start(); floyd.DoWork(graph); sw.Stop(); graph.FloydTime = sw.Elapsed; var PageRank = new PageRank(graph); graph.Iterations = PageRank.DoWork(); }
public void DistanceMatrixTest() { var converter = new OBConversion(); converter.SetInFormat("smi"); var mol = new OBMol(); converter.ReadString(mol, "CC=C"); var dMat = new FloydWarshall(mol, false, false).DistanceMatrix; Assert.AreEqual(0d, dMat.Get(0, 0)); Assert.AreEqual(1d, dMat.Get(0, 1)); Assert.AreEqual(2d, dMat.Get(0, 2)); Assert.AreEqual(1d, dMat.Get(1, 0)); Assert.AreEqual(0d, dMat.Get(1, 1)); Assert.AreEqual(1d, dMat.Get(1, 2)); Assert.AreEqual(2d, dMat.Get(2, 0)); Assert.AreEqual(1d, dMat.Get(2, 1)); Assert.AreEqual(0d, dMat.Get(2, 2)); dMat = new FloydWarshall(mol, true, false).DistanceMatrix; Assert.AreEqual(0d, dMat.Get(0, 0)); Assert.AreEqual(1d, dMat.Get(0, 1)); Assert.AreEqual(1.5, dMat.Get(0, 2)); Assert.AreEqual(1d, dMat.Get(1, 0)); Assert.AreEqual(0d, dMat.Get(1, 1)); Assert.AreEqual(0.5, dMat.Get(1, 2)); Assert.AreEqual(1.5, dMat.Get(2, 0)); Assert.AreEqual(0.5, dMat.Get(2, 1)); Assert.AreEqual(0d, dMat.Get(2, 2)); }
public void Test() { var weights = new DenseGraph <int?>(new int?[, ] { { 0000, 0007, 0009, null, null, 0014 }, { 0007, 0000, 0010, 0014, null, null }, { 0009, 0010, 0000, 0011, null, 0002 }, { null, 0014, 0011, 0000, 0006, null }, { null, null, null, 0006, 0000, 0009 }, { 0014, null, 0002, null, 0009, 0000 }, }); var floydWarshall = new FloydWarshall(weights); var floydWarshallResult = floydWarshall.GetResult(); var dijkstra = new Dijkstra(weights); for (var i = 0; i < weights.VertexCount; i++) { var dijkstraResult = dijkstra.GetResult(i); Assert.Equal(floydWarshallResult.distance.SliceRow(i), dijkstraResult.Select(x => x.Distance)); for (var j = 0; j < weights.VertexCount; j++) { Assert.Equal(floydWarshall.GetPath(floydWarshallResult.next, i, j), dijkstra.GetPath(dijkstraResult, i, j)); } } }
private void solveVRP(World world) { // Spawns objects that visualize the points of interest spawnPointOfInterestObjects(); // Initialize visibility graph List <Vector2> addPoints = new List <Vector2> (world.pointsOfInterest); foreach (var point in world.startPositions) { addPoints.Add(point); } foreach (var point in world.goalPositions) { addPoints.Add(point); } VisibilityGraph.initVisibilityGraph(world, addPoints); // Execute FloydWarshall algorithm on visibility graph to get shortest paths FloydWarshall fw = new FloydWarshall(world.visibilityGraph); float[,] floydWarshallDistMatrix = fw.findShortestPaths(); // Get number of obstacle vertices obstacleVertCount = world.graphVertices.Count - world.pointsOfInterest.Length - agents.Length * 2; // Remove obstacle vertex rows and columns from the distance matrix as GA does not work with them to find a solution float[,] distanceMatrix = getSubArray(floydWarshallDistMatrix, obstacleVertCount); // Use the genetic algorithm for the Vehicle Routing Problem GeneticAlgorithm ga = new GeneticAlgorithm(populationSize, populationSize, world.pointsOfInterest.Length, agents.Length, distanceMatrix, 0.02f, geneticAlgorithmIterations, false, 0.04f, 0.01f, true); ga.generationalGeneticAlgorithm(); List <int> solution = ga.getFittestIndividual(); solution = GeneticAlgorithmHelper.includeSolutionGoals(solution, world.pointsOfInterest.Length, agents.Length); // Reconstruct path including intermediate obstacle vertex nodes for (int i = 0; i < solution.Count; i++) { solution [i] += obstacleVertCount; } List <int> reconstructedSolution = reconstructShortestPath(solution, fw, agents.Length); // Visualize the reconstructed path (solution including intermediate nodes) Visualizer.visualizeVRPsolution(world.graphVertices, reconstructedSolution, agents.Length, obstacleVertCount); solutionList = GeneticAlgorithmHelper.splitSolution(solution, world.graphVertices.Count, agents.Length); for (int i = 0; i < solutionList.Count; i++) { solutionList[i] = reconstructShortestPath(solutionList [i], fw, agents.Length); } solutionCoordinates = getSolutionCoordinates(solutionList); }
/// <summary> /// Test case for paths of length 0 and 1, and an impossible path /// </summary> //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testMinimal() public virtual void TestMinimal() { Graph.makeEdge("a", "b", "cost", ( double )1); Graph.makeEdge("a", "c", "cost", ( float )1); Graph.makeEdge("a", "d", "cost", ( long )1); Graph.makeEdge("a", "e", "cost", 1); Graph.makeEdge("b", "c", "cost", ( double )1); Graph.makeEdge("c", "d", "cost", ( sbyte )1); Graph.makeEdge("d", "e", "cost", ( short )1); Graph.makeEdge("e", "b", "cost", ( sbyte )1); FloydWarshall <double> floydWarshall = new FloydWarshall <double>(0.0, double.MaxValue, Direction.OUTGOING, CommonEvaluators.doubleCostEvaluator("cost"), new Org.Neo4j.Graphalgo.impl.util.DoubleAdder(), double?.compareTo, Graph.AllNodes, Graph.AllEdges); assertEquals(0.0, floydWarshall.GetCost(Graph.getNode("a"), Graph.getNode("a")), 0.0); assertEquals(1.0, floydWarshall.GetCost(Graph.getNode("a"), Graph.getNode("b")), 0.0); assertEquals(floydWarshall.GetCost(Graph.getNode("b"), Graph.getNode("a")), double.MaxValue, 0.0); }
public void TestFiles() { var files = new [] { "g1.txt", "g2.txt" , "g3.txt" }; var res = new List<long?>(); foreach (var fl in files) { var g = GetGraphFrom(fl); var n = g.GetLength(0); var fw = new FloydWarshall(g, n); fw.ComputeAllPairsShortestPath(); res.Add(fw.GetShortestDistance()); } }
public void CorrectMatrixTest() { var graph = new DirectedWeightedGraph <int>(10); var vertex1 = graph.AddVertex(1); var vertex2 = graph.AddVertex(2); var vertex3 = graph.AddVertex(3); var vertex4 = graph.AddVertex(4); var vertex5 = graph.AddVertex(5); graph.AddEdge(vertex1, vertex2, 3); graph.AddEdge(vertex1, vertex5, -4); graph.AddEdge(vertex1, vertex3, 8); graph.AddEdge(vertex2, vertex5, 7); graph.AddEdge(vertex2, vertex4, 1); graph.AddEdge(vertex3, vertex2, 4); graph.AddEdge(vertex4, vertex3, -5); graph.AddEdge(vertex4, vertex1, 2); graph.AddEdge(vertex5, vertex4, 6); var actualDistances = new double[, ] { { 0, 1, -3, 2, -4 }, { 3, 0, -4, 1, -1 }, { 7, 4, 0, 5, 3 }, { 2, -1, -5, 0, -2 }, { 8, 5, 1, 6, 0 }, }; var floydWarshaller = new FloydWarshall <int>(); floydWarshaller.Run(graph).Should().Equal(actualDistances); }
/// <summary> /// Test case for extracting paths /// </summary> //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testPath() public virtual void TestPath() { Graph.makeEdge("a", "b", "cost", ( double )1); Graph.makeEdge("b", "c", "cost", ( float )1); Graph.makeEdge("c", "d", "cost", 1); Graph.makeEdge("d", "e", "cost", ( long )1); Graph.makeEdge("e", "f", "cost", ( sbyte )1); FloydWarshall <double> floydWarshall = new FloydWarshall <double>(0.0, double.MaxValue, Direction.OUTGOING, CommonEvaluators.doubleCostEvaluator("cost"), new Org.Neo4j.Graphalgo.impl.util.DoubleAdder(), double?.compareTo, Graph.AllNodes, Graph.AllEdges); IList <Node> path = floydWarshall.GetPath(Graph.getNode("a"), Graph.getNode("f")); assertEquals(6, path.Count); assertEquals(path[0], Graph.getNode("a")); assertEquals(path[1], Graph.getNode("b")); assertEquals(path[2], Graph.getNode("c")); assertEquals(path[3], Graph.getNode("d")); assertEquals(path[4], Graph.getNode("e")); assertEquals(path[5], Graph.getNode("f")); }
public void testFloyd() { FloydInfo ans = FloydWarshall.AllShortestPaths(fg); long m = long.MaxValue; long [,] correct = new long[5, 5] { { 0, m, m, m, m }, { m, 0, 1, 2, 1 }, { m, 1, 0, 2, 1 }, { m, 2, 2, 0, 1 }, { m, 1, 1, 1, 0 } }; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { Console.Write(ans.GetDistance(i, j) + " "); } Console.WriteLine(); } Assert.AreEqual(correct, ans.map); }
public void UnitFloydWarshall() { FloydWarshall newFloyd = new FloydWarshall(); newFloyd.MaxValue = 9999; newFloyd.TwoDimensionArray = new int[5, 5] { { 0, 3, 8, 9999, -4 }, { 9999, 0, 9999, 1, 7 }, { 9999, 4, 0, 9999, 9999 }, { 2, 9999, -5, 0, 9999 }, { 9999, 9999, 9999, 6, 0 } }; //newFloyd.dist = new int[5, 5] { { 0, int.MaxValue, int.MaxValue, 2, int.MaxValue }, { 3, 0, 4, int.MaxValue, int.MaxValue }, { 8, int.MaxValue, 0, -5, int.MaxValue }, { int.MaxValue, 1, int.MaxValue, 0, 6 }, { -4, 7, int.MaxValue, int.MaxValue, 0 } }; //newFloyd.dist = new int[5, 5] { { 0, int.MaxValue, 3, int.MaxValue, 1 }, // { 5, 0, int.MaxValue, int.MaxValue, 3 }, // { int.MaxValue, 2, 0, 4, int.MaxValue }, // { 2, int.MaxValue, int.MaxValue, 0, 0 }, // { int.MaxValue, int.MaxValue, 7, 1, 0 } }; //newFloyd.dist = new int[5, 5] { { 0, 5, int.MaxValue, 2, int.MaxValue }, // { int.MaxValue, 0, 2, int.MaxValue, int.MaxValue }, // { 3, int.MaxValue, 0, int.MaxValue, 7 }, // { int.MaxValue, int.MaxValue, 4, 0, 1 }, // { 1, 3, int.MaxValue, int.MaxValue, 0 } }; //newFloyd.dist = new int[4, 4] { {0, 5, 9999, 10}, // {9999, 0, 3, 9999}, // {9999, 9999, 0, 1}, // {9999, 9999, 9999, 0} }; newFloyd.NumberOfNodes = 5; newFloyd.Floyd_warshallWork(); List <int> rez = new List <int>(); newFloyd.GetPath(2, 4, ref rez); string result = ""; foreach (var item in rez) { result += item; } Assert.AreEqual("21304", result); }
void Start() { FloydWarshall fw = new FloydWarshall(); playerHealth = GameObject.FindGameObjectWithTag("Player").GetComponent <PlayerHealth>(); gameManage = GameObject.FindGameObjectWithTag("GameManage").GetComponent <GameManage>(); npc = GameObject.FindGameObjectsWithTag("NPC"); agents = new NavMeshAgent[npc.Length]; startPos = new Transform[npc.Length]; dest1 = new Transform[npc.Length]; dest2 = GameObject.FindGameObjectWithTag("Destination").GetComponent <Transform>(); _npc = new Transform[npc.Length]; destPoint = new Vector3[npc.Length]; enemyHealth = new EnemyHealth[npc.Length]; destCollider2 = GameObject.FindGameObjectWithTag("Destination").GetComponent <BoxCollider>(); animator = new Animator[npc.Length]; sugeno = new Sugeno[npc.Length]; for (int i = 0; i < npc.Length; i++) { sugeno[i] = npc[i].GetComponent <Sugeno>(); startPos[i] = npc[i].GetComponent <Transform>(); startPosList.Add(startPos[i]); dest1[i] = fw.dest1[i + 6]; dest1List.Add(dest1[i]); destPoint[i] = dest1[i].position; destPointList.Add(destPoint[i]); enemyHealth[i] = npc[i].GetComponentInChildren <EnemyHealth>(); enemyHealthList.Add(enemyHealth[i]); agents[i] = npc[i].GetComponent <NavMeshAgent>(); agentsList.Add(agents[i]); _npc[i] = npc[i].GetComponent <Transform>(); _npcList.Add(_npc[i]); //agents[i].destination = dest1List[i].position; agents[i].speed = speedEnemy; animator[i] = agents[i].GetComponent <Animator>(); } }
/// <summary> /// Return the reconstructed shortest path indices given the indices of a path /// as well as the FloydWarshall object used to find the shortest paths. /// </summary> public List <int> reconstructShortestPath(List <int> path, FloydWarshall fw, int vehicles) { List <int> reconstructedPath = new List <int> (); for (int i = 0; i < path.Count - 1; i++) { reconstructedPath.Add(path[i]); // If the current node is a goal do not draw a path between it and the next node if (path [i] >= fw.getNodeCount() - vehicles) { continue; } // For each pair of nodes i and i + 1 in path add the intermediate nodes List <int> tmpPath = fw.reconstructShortestPath(path[i], path[i + 1]); for (int j = 1; j < tmpPath.Count - 1; j++) { reconstructedPath.Add(tmpPath [j]); } } reconstructedPath.Add(path[path.Count - 1]); return(reconstructedPath); }
public List <OneStepPlan> getPlan() { if (shortestPathsFinder == null) { shortestPathsFinder = new FloydWarshall(world.visibilityGraph); shortestDists = shortestPathsFinder.findShortestPaths(); } // Get initial greedy solution List <OneStepPlan> initialSolution; switch (weaponType) { case WeaponTypeEnum.Shotgun: initialSolution = getShotgunInitialSolution(); return(initialSolution); case WeaponTypeEnum.Rifle: initialSolution = getRifleInitialSolution(); return(initialSolution); } return(null); }
private static int[,] RunFloydWarshall(Vertex[] vertices) { return(FloydWarshall.Run(vertices)); }
public void AllPairsShortestPathTest() { var n = 7; var graph = Common.CreateEmptyAdjacencyMatrix(n); var expected = Common.CreateEmptyAdjacencyMatrix(n); graph[0, 1] = 2; graph[0, 2] = 5; graph[0, 6] = 10; graph[1, 2] = 2; graph[1, 4] = 11; graph[2, 6] = 2; graph[6, 5] = 11; graph[4, 5] = 1; graph[5, 4] = -2; expected[0, 0] = 0; expected[0, 1] = 2; expected[0, 2] = 4; expected[0, 3] = double.PositiveInfinity; expected[0, 4] = double.NegativeInfinity; expected[0, 5] = double.NegativeInfinity; expected[0, 6] = 6; expected[1, 0] = double.PositiveInfinity; expected[1, 1] = 0; expected[1, 2] = 2; expected[1, 3] = double.PositiveInfinity; expected[1, 4] = double.NegativeInfinity; expected[1, 5] = double.NegativeInfinity; expected[1, 6] = 4; expected[2, 0] = double.PositiveInfinity; expected[2, 1] = double.PositiveInfinity; expected[2, 2] = 0; expected[2, 3] = double.PositiveInfinity; expected[2, 4] = double.NegativeInfinity; expected[2, 5] = double.NegativeInfinity; expected[2, 6] = 2; expected[3, 0] = double.PositiveInfinity; expected[3, 1] = double.PositiveInfinity; expected[3, 2] = double.PositiveInfinity; expected[3, 3] = 0; expected[3, 4] = double.PositiveInfinity; expected[3, 5] = double.PositiveInfinity; expected[3, 6] = double.PositiveInfinity; expected[4, 0] = double.PositiveInfinity; expected[4, 1] = double.PositiveInfinity; expected[4, 2] = double.PositiveInfinity; expected[4, 3] = double.PositiveInfinity; expected[4, 4] = double.NegativeInfinity; expected[4, 5] = double.NegativeInfinity; expected[4, 6] = double.PositiveInfinity; expected[5, 0] = double.PositiveInfinity; expected[5, 1] = double.PositiveInfinity; expected[5, 2] = double.PositiveInfinity; expected[5, 3] = double.PositiveInfinity; expected[5, 4] = double.NegativeInfinity; expected[5, 5] = double.NegativeInfinity; expected[5, 6] = double.PositiveInfinity; expected[6, 0] = double.PositiveInfinity; expected[6, 1] = double.PositiveInfinity; expected[6, 2] = double.PositiveInfinity; expected[6, 3] = double.PositiveInfinity; expected[6, 4] = double.NegativeInfinity; expected[6, 5] = double.NegativeInfinity; expected[6, 6] = 0; var distances = FloydWarshall.AllPairsShortestPath(graph); Common.AssertEqual(expected, distances); }
static void Main(string[] args) { string[] TestArray = new[] { "Kaas", "Hond", "Miami", "Piet" }; int[] TestintArrayOrderd = new[] { 1, 3, 4, 5, 7, 12, 14, 16 }; int[] TestintArrayUnOrderd = new int[] { 8, 1, 6, 3, 7, 18, 13, 23, 17, 15, 5 }; int[] TestInsertionSort = TestintArrayUnOrderd.InsertionSort(); /*foreach (var item in TestInsertionSort) * { * Console.WriteLine(item); * }*/ /*BinaryTree<int> boom = new BinaryTree<int>(); * boom.Add(10); * boom.Add(30); * boom.Add(5); * boom.Add(6); * boom.Add(4); * boom.Add(2); * boom.Add(3); * * boom.Remove(30); * boom.Remove(10);*/ /*hashtable<int, string> hashtable = new hashtable<int, string>(); * hashtable.add(900, "Kaas"); * hashtable.add(300, "mount"); * hashtable.add(548, "jfksdl"); * hashtable.add(17, "Dion"); * hashtable.add(924, "ibny"); * hashtable.add(305, "7ddv8"); * hashtable.add(1235, "jkiji"); * hashtable.add(354, "month"); * hashtable.add(7531, "cheese"); * hashtable.add(235, "8687bn"); * hashtable.add(2014, "Kaaujuis"); * hashtable.add(932, "1234"); * hashtable.add(231856, "sinterklaas"); * hashtable.add(1, "3"); * hashtable.add(3654, "mount"); * hashtable.add(3025, "sint"); * hashtable.add(78, "6"); * hashtable.add(360, "8"); * hashtable.add(15, "Leer"); * hashtable.add(28, "Mond"); * * Option<KeyValuePair<int, string>> print = hashtable.search(900); * * Console.WriteLine(print.data.value);*/ /*LinkedList<int> lijst = new LinkedList<int>(); * lijst.InsertOnStart(1); * lijst.InsertOnStart(9); * lijst.InsertOnStart(5); * lijst.InsertOnAfter(2, 9); * * node<int> TMPlijst = lijst.StartingNode; * * while(TMPlijst != null) * { * Console.WriteLine(TMPlijst.Data); * TMPlijst = TMPlijst.Next; * }*/ double[,] graph = new double[, ] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; FloydWarshall t = new FloydWarshall(graph); var result = t.FloydWarshallAlgorithme(); foreach (var item in result.Item1) { Console.WriteLine(item); } Console.WriteLine("-------"); foreach (var item in result.Item2) { Console.WriteLine(item); } Console.ReadKey(); }
public override void Execute() { // build the graph Graph <T> graph = new Graph <T>(); //graph.AddUndirectedEdge("Frankfurt", "Wiesbaden", 40); //graph.AddUndirectedEdge("Frankfurt", "Mainz", 30); //graph.AddUndirectedEdge("Mainz", "Wiesbaden", 15); //graph.AddUndirectedEdge("Rüdesheim", "Geisenheim", 4); foreach (var matchpair in this.matches) { graph.AddUndirectedEdge(matchpair.From, matchpair.To, matchpair.Cost); } // uses the FloyWarshall algorithm to compute the transitive closure this // means to determine all possible ways in a graph (so you can check, if nodes have a way to each other in the graph) FloydWarshall <T> transClosureAlgorithm = new FloydWarshall <T>(); transClosureAlgorithm.Execute(graph); // now for all nodes in the graph e.g (Wiesbaden, Mainz, Frankfurt, Rüdesheim, Geisenheim) for (int i = 0; i < transClosureAlgorithm.CostMatrix.GetLength(0); i++) { var cluster = new List <MatchPair <T> >(); T startNode = transClosureAlgorithm.Graph.Nodes[i].Value; // loop through all nodes in the graph e.g (Wiesbaden, Mainz, Frankfurt, Rüdesheim, Geisenheim) for (int j = 0; j < transClosureAlgorithm.CostMatrix.GetLength(0); j++) { T endNode = transClosureAlgorithm.Graph.Nodes[j].Value; var cost = transClosureAlgorithm.CostMatrix[i, j]; // only when a way in the graph exits (waycosts != Infinity) // and it is not himself (startNode != endNode) if (cost != transClosureAlgorithm.Graph.Infinity && !startNode.Equals(endNode)) { // a way exists var matchPair = new MatchPair <T>(startNode, endNode, cost); // checked if it is in the original list if (this.matches.Contains(matchPair)) { // check, if a connection point (startnode or endnode) is already in another cluster var found = this.IsInOtherCluster(matchPair); if (!found) { // add to the new cluster cluster.Add(matchPair); } } } } // when a cluster was build, add to the clusterlist if (cluster.Count > 0) { this.clusters.Add(cluster); } // clusters will be e.g. // Cluster 1: (Frankfurt, Wiesbaden, Mainz) // Cluster 2: (Rüdesheim, Geisenheim) } }
private static bool[] RunFloydWarshall(Vertex[] vertices, int source) { int[,] depths = FloydWarshall.Run(vertices); return(Enumerable.Range(0, vertices.Length).Select(i => depths[source, i] != int.MaxValue).ToArray()); }
public void Run() { Console.WriteLine("Choose file:"); // Prompt Console.WriteLine("1 - tinyEWD.txt"); // Prompt Console.WriteLine("2 - mediumEWD.txt"); // Prompt //Console.WriteLine("3 - mediumEWG.txt"); // Prompt Console.WriteLine("or quit"); // Prompt var fileNumber = Console.ReadLine(); string fileName; switch (fileNumber) { case "1": fileName = "tinyEWD.txt"; break; case "2": fileName = "mediumEWD.txt"; break; //case "3": // fileName = "largeEWG.zip"; // break; case "quit": return; default: return; } var @in = new In($"Files\\Graphs\\{fileName}"); var lines = @in.ReadAllLines(); var lineIterator = 0; var v = 0; var e = 0; var edges = new List <DirectedEdge>(); foreach (var line in lines) { if (lineIterator == 0) { v = Convert.ToInt32(line); } if (lineIterator == 1) { e = Convert.ToInt32(line); } if (lineIterator > 1) { var lineSplitted = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); var ve = Convert.ToInt32(lineSplitted[0]); var we = Convert.ToInt32(lineSplitted[1]); var weight = Convert.ToDouble(lineSplitted[2], CultureInfo.InvariantCulture); var edge = new DirectedEdge(ve, we, weight); edges.Add(edge); } lineIterator++; } var adjMatrixEdgeWeightedDigraph = new AdjMatrixEdgeWeightedDigraph(v, e, edges); Console.WriteLine(adjMatrixEdgeWeightedDigraph); // run Floyd-Warshall algorithm var spt = new FloydWarshall(adjMatrixEdgeWeightedDigraph); // print all-pairs shortest path distances Console.Write(" "); for (var vv = 0; vv < adjMatrixEdgeWeightedDigraph.V; vv++) { Console.Write($"{vv} "); } Console.WriteLine(); for (var vv = 0; vv < adjMatrixEdgeWeightedDigraph.V; vv++) { Console.Write($"{vv}: "); for (var w = 0; w < adjMatrixEdgeWeightedDigraph.V; w++) { Console.Write(spt.HasPath(vv, w) ? $"{spt.Dist(vv, w):00} " : " Inf "); } Console.WriteLine(); } // print negative cycle if (spt.HasNegativeCycle) { Console.WriteLine("Negative cost cycle:"); foreach (var edge in spt.NegativeCycle()) { Console.WriteLine(edge); } Console.WriteLine(); } // print all-pairs shortest paths else { for (var vv = 0; vv < adjMatrixEdgeWeightedDigraph.V; vv++) { for (var w = 0; w < adjMatrixEdgeWeightedDigraph.V; w++) { if (spt.HasPath(vv, w)) { Console.Write($"{vv} to {w} {spt.Dist(vv, w):00} "); foreach (var edge in spt.Path(vv, w)) { Console.Write($"{edge} "); } Console.WriteLine(); } else { Console.Write($"{vv} to {w} no path{Environment.NewLine}"); } } } } Console.ReadLine(); }
public void CanCalculateMinDistancesForGraphWithCycles() { var sut = new FloydWarshall(); var graph = new WeightedGraphVertex[4]; var node1 = new WeightedGraphVertex { Edges = new System.Collections.Generic.List <WeightedGraphNodeEdge> { new WeightedGraphNodeEdge { To = 2, Weight = 3 }, new WeightedGraphNodeEdge { To = 3, Weight = 0 }, } }; var node2 = new WeightedGraphVertex { Edges = new System.Collections.Generic.List <WeightedGraphNodeEdge> { new WeightedGraphNodeEdge { To = 0, Weight = -2 }, new WeightedGraphNodeEdge { To = 3, Weight = 1 }, } }; var node3 = new WeightedGraphVertex { Edges = new System.Collections.Generic.List <WeightedGraphNodeEdge> { new WeightedGraphNodeEdge { To = 3, Weight = 5 }, } }; var node4 = new WeightedGraphVertex { Edges = new System.Collections.Generic.List <WeightedGraphNodeEdge> { new WeightedGraphNodeEdge { To = 1, Weight = 4 }, } }; graph[0] = node1; graph[1] = node2; graph[2] = node3; graph[3] = node4; var(distances, path) = sut.MinDistances(graph); Assert.Collection(distances[0], arg => Assert.Equal(0, arg), arg => Assert.Equal(4, arg), arg => Assert.Equal(3, arg), arg => Assert.Equal(0, arg)); Assert.Collection(distances[1], arg => Assert.Equal(-2, arg), arg => Assert.Equal(0, arg), arg => Assert.Equal(1, arg), arg => Assert.Equal(-2, arg)); Assert.Collection(distances[2], arg => Assert.Equal(7, arg), arg => Assert.Equal(9, arg), arg => Assert.Equal(0, arg), arg => Assert.Equal(5, arg)); Assert.Collection(distances[3], arg => Assert.Equal(2, arg), arg => Assert.Equal(4, arg), arg => Assert.Equal(5, arg), arg => Assert.Equal(0, arg)); }
static void Main(string[] args) { // StringProblems //Test calls for Reverse string string input = "jacob"; Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray()))); input = "jake"; Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray()))); input = ""; Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray()))); input = "jdshjdh@#$%^&)"; Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray()))); ReplaceSpaces.TestReplaceSpacesInplace(); Anagrams.TestIsAnagramAlgo(); StringRotation.TestIsThisRotatedString(); RemoveDuplicates.TestRemoveDuplicatesFromString(); StringToLongConverter.TestStringToLong(); RegexMatching.TestMatch(); SumOfTwoNumbersInArray.TestSumOfTwoNumbersInArray(); SumOfThreeNumbersInArray.TestSumOfThreeNumbersInArray(); PairInSortedArrayClosestToAParticularValue.TestPairInSortedArrayClosestToAParticularValue(); PalindromeInStringPermutation.TestPalindromeInStringPermutation(); EditDistanceBetweenStrings.TestEditDistanceBetweenStrings(); AnagramIsPalindrome.TestAnagramIsPalindrome(); GreatestPalindrome.TestGreatestPalindrome(); ReverseStringWithoutVowels.TestReverseStringWithoutVowels(); LongestSubstringWithKDistinctChars.TestLongestSubstringWithKDistinctChars(); // Pattern Matching NativePatternMatching.TestNativePatternMatching(); KMPPatternMatching.TestKMPPatternMatching(); BoyerMoorePatternMatching.TestPatternMatching(); RabinKarp.TestRabinKarp(); //Console.ReadLine(); //Array Problems ArrayOfNumsIncrement.TestIncrementArrayOfNumbers(); MajorityElement.TestFindMajorityElement(); Merge2SortedArrays.TestMergeSortedArrays(); MaxDistanceInArray.TestMaxDistanceInArray(); MovingAverage.TestMovingAverage(); TotalAverage.TestTotalAverage(); ArrayWithGreaterElementToRight.TestArrayWithGreaterElementToRight(); WaterCollectedInPuddleShownByHistogram.TestWaterCollectedInPuddleShownByHistogram(); CountOfPairsWhichSumUpToGivenSum.TestCountOfPairsWhichSumUpToGivenSum(); //Median.TestGetMedianOf2SortedArray(); // Sorting Problems SelectionSort.TestSorting(); BubbleSort.TestSorting(); InsertionSort.TestSorting(); ShellSort.TestSorting(); MergeSort.TestMergeSort(); QuickSort.TestQuickSort(); HeapSortTester.TestHeapSort(); CountingSort.TestSorting(); RadixSort.TestRadixSort(); DutchNationalFlag.TestDutchNationalFlag(); SortedSquares.TestSortedSquares(); // Matrix Problem Rotate_Matrix_90_degree.TestRotateMatrix(); Matrix_Column_Rows_0.TestMakeRowColZero1(); Matrix_Column_Rows_0.TestMakeRowColZero2(); RotateMatrix180.TestRotateMatrix180(); SumOfMatrixElementsFormedByRectangleWithCoordinates.TestSumOfMatrixElements(); SortedArrayFromSortedMatrix.TestSortedArrayFromSortedMatrix(); SearchWordInMatrix.TestSearchWordInMatrix(); MaxOnesInRow.TestMaxOnesInRow(); MatrixAsTriangle.TestMatrixAsTriangle(); MinRangeInMatrix.TestMinRangeInMatrix(); PrintMatrixAsSnake.TestPrintMatrixAsSnake(); PrintMatrixInSpiral.TestPrintMatrixInSpiral(); MaxSqAreaInBinaryMatrix.TestMaxRectAreaInBinaryMatrix(); TicTacToeWinner.TestTicTacToeWinner(); WaterfallCreation.TestWaterfallCreation(); // Linked list Problems DeleteLinkedListNode.TestDeleteFirstNode(); DeleteDuplicatesFromLinkedList.TestDeleteDuplicates(); NthLastElementOfLinkedList.TestNthLastNodeOfLinkedList(); DeleteNodeWithDirectReference.TestDeleteNode(); AddNumbers.TestAddNumbersRepresentedByLinkedList(); CopyLinkedListWithRandomNode.TestGetCopiedLinkedListWithRandomNode(); CommonElementInTwoLinkedList.TestCommonElement(); ReverseAdjacentNodesInLinkedList.TestReverseAdjacentNodes(); MergeSortedLinkedList.TestMerge(); CycleInLinkedList.TestStartOfCycleInLinkedList(); MedianForCircularLinkedList.TestGetMedian(); ReverseLinkedList.TestReverseLinkedList(); SortedCircularLinkedList.TestCircularLinkedList(); // stack and queue problem ThreeStackWithOneArray.TestThreeStackWithOneArray(); StackWithMinElement.TestStackWithMinElement(); StackOfPlates.TestStackOfPlates(); SortAStack.TestSortAStackAscending(); WellFormedExpression.TestWellFormedExpression(); QueueVia2Stack.TestQueueVia2Stack(); LRUCache.TestLRUCache(); EvaluatePrefixNotation.TestGetPrefixNotationResult(); EvaluateInflixNotation.TestGetInflixNotationResults(); EvaluatePostfixNotation.TestGetPostfixNotationResult(); TestCircularQueue.TestCircularQueueWithDifferentCases(); LargestAreaInHistogram.TestLargestAreaInHistogram(); TextEditerWithUndo.TestTextEditerWithUndo(); //Recursion Problem TowerOfHanoi.TestTowerOfHanoi(); MaxSumOfConsecutiveNums.TestMaxSumOfConsecutiveNums(); // Back tracking problems Sudoku.TestSudokuSolver(); HamiltonianCycle.TestHamiltonianCycle(); GraphColoringWithMColors.TestGraphColoringWithMColors(); MakeLargestIsland.TestMakeLargestIsland(); //Misc Problem MinNumOfCoins.TestMinNumOfCoins(); IsPrime.TestCheckPrime(); SquareRoot.TestCalculateSquareRoot(); CreditCardCheck.TestLuhnAlgo(); ExcelFirstRowConversion.TestCovertExcelColumnToLong(); Skyline.TestSkyline(); SumOfSquaresWithoutMultiplication.TestSumOfSquares(); MergeIntervals.TestMergeIntervals(); WidthOfCalendar.TestWidthOfCalendar(); JosephusProblem.TestJosephusProblem(); // Permutation and Combination problem ShuffleAList.TestFisherYatesAlgo(); CombinationsOfBinaryString.TestCombinationsOfBinaryString(); AllCombinationsOfString.TestAllCombinationsOfString(); AllPermutationsOfString.TestAllPermutationsOfString(); PhoneNumberToWords.TestPhoneNumberToWords(); AllNumbersInRangeWithDifferentDigits.TestAllNumbersInRangeWithDifferentDigits(); DivideSetIntoTwoEqualSetsWithMinSumDiff.TestDivideSetIntoTwoEqualSetsWithMinSumDiff(); PowerSet.TestPowerSet(); AllCombinationsOfParenthesis.TestAllCombinationsOfParenthesis(); GoodDiceRoll.TestGoodDiceRoll(); PermutationsOfValidTime.TestPermutationsOfValidTime(); // Tree Problems TreeFromExpression.TestCreateTreeFromExpression(); TestBinarySearchTree.TestDifferentOperationsOnBST(); AncestorOfTwoNodesInBST.TestAncestorOfTwoNodesInBST(); CheckBTisBST.TestCheckBTisBST(); MaxSumOnTreeBranch.TestMaxSum(); WalkTheTree.TestWalkTheTree(); SkewedBSTToCompleteBST.TestConvertSkewedBSTToCompleteBST(); CheckIfTheTreeIsBalanced.TestIsTreeBalanced(); LinkedListOfTreeNodesAtEachDepth.TestCreateLinkedListOfTreeNodesAtEachDepth(); PrintBinaryTreeNodeAtEachLevel.TestPrintBinaryTreeNodeAtEachLevel(); PrintBinaryTreeNodeAtEachLevelSpirally.TestPrintBinaryTreeNodeAtEachLevelSpirally(); TreeSubtreeOfAnother.TestMatchTree(); AncestorOfTwoNodesInBT.TestGetAncestorOfTwoNodesInBT(); AncestorOfMultiNodesInBT.TestAncestorOfMultiNodesInBT(); LinkedListFromLeavesOfBT.TestLinkedListFromLeavesOfBT(); ExteriorOfBT.TestPrintExteriorOfBT(); DepthOfTree.TestGetDepthOfTree(); TreeToColumns.TestTreeToColumns(); KthSmallestElementFromBST.TestKthSmallestElementFromBST(); MakeBSTFromPreOrder.TestMakeBSTFromPreOrder(); MirrorATree.TestMirrorATree(); CloneABTWithRandPointer.TestCloneABTWithRandPointer(); TreeWithInorderAndPreorder.TestTreeWithInorderAndPreorder(); TreeWithInorderAndPostorder.TestTreeWithInorderAndPostorder(); TreePathSumsToValue.TestTreePathSumsToValue(); AllPathInNArayTree.TestAllPathInNArayTree(); SerializeDeserializeBinaryTree.TestSerializeDeserializeBinaryTree(); SerializeDeserializeAnNaryTree.TestSerializeDeserializeAnNaryTree(); AncestorOfTwoNodesInNaryTree.TestAncestorOfTwoNodesInNaryTree(); AbsOfMaxAndSecondMaxDepthInBT.TestGetAbsOfMaxAndSecondMaxDepthInBT(); // Trie problems CreateAndSearchSimpleTrie.TestCreateAndSearchSimpleTrie(); // ToDo: have a problem of suffix trees ShortestPrefix.TestGetShortestPrefixNotPresentInStringSet(); // Dynamic Programming problems LongestCommonSubsequence.TestGetLongestCommonSubsequence(); LongestPalindromeSubString.TestGetLongestPalindromeSubString(); LongestPalindromicSubsequence.TestGetLongestPalindromicSubsequence(); MaximumAs.TestGetMaximumAs(); MinNumberOfJumps.TestGetMinimumNumberOfJumps(); LongestCommonSubString.TestGetLongestCommonSubString(); KnapSackProblem.TestGetTheMaximumValueWithLimitedWeight(); TreeCuttingProblem.TestGetTreeCuttingToMaximizeProfits(); WordBreaking.TestBreakTheWords(); DistanceOfWords.TestDistanceOfWords(); LongestIncreasingSubSequence.TestLongestIncreasingSubSequence(); MinCostPath.TestMinCostPath(); DifferentWaysForCoinChange.TestDifferentWaysForCoinChange(); MatrixMultiplication.TestMatrixMultiplication(); BinomialCoefficient.TestBinomialCoefficient(); BoxStacking.TestBoxStacking(); WordWrapping.TestWordWrapping(); MaxSubMatrixWithAllOnes.TestMaxSubMatrixWithAllOnes(); LongestSubStringWithEqualSum.TestLongestSubStringWithEqualSum(); PartitionArrayIntoEqualSumSets.TestPartitionArrayIntoEqualSumSets(); MaxSumRectangle.TestMaxSumRectangle(); RegularExpressionMatch.TestRegularExpressionMatch(); NumRepresentedByPerfectSquares.TestNumRepresentedByPerfectSquares(); LongestCommonSubsequenceInSameString.TestLongestCommonSubsequenceInSameString(); StringDecodeAsAlphabets.TestStringDecodeAsAlphabets(); BalloonBursting.TestBalloonBursting(); TravellingSalesmanProblem.TestTravellingSalesmanProblem(); MaxSumWithoutAdjacentElements.TestMaxSumWithoutAdjacentElements(); MaxPathThroughMatrix.TestMaxPathThroughMatrix(); BrickLaying.TestBrickLaying(); JobSchedullingWithConstraints.TestJobSchedullingWithConstraints(); EggDropMinTrials.TestEggDropMinTrials(); // Graph Problems ShortestPath.TestGetShortestPathBetween2Vertex(); CycleInDirectedGraph.TestIsCycleInDirectedGraph(); CycleInUnDirectedGraph.TestIsCycleInUnDirectedGraph(); SolveAMaze.TestSolveAMaze(); AllPathsGivenStartEndVertex.TestGetAllPathsInGraphFromStartVertexToEndVertex(); AllPaths.TestGetAllPathsInGraphFromStartVertex(); ColorVertices.TestColorVerticesWithDifferentColor(); CheckBipartiteGraph.TestCheckBipartiteGraph(); TransformOneWordToAnother.TestGetTransformation(); ConstraintsVerification.TestConstraintsVerification(); ExtendedContactsInSocialNetwork.TestComputeExtendedContacts(); CourseScheduling.TestCourseScheduling(); SnakeAndLadder.TestSnakeAndLadder(); IsGraphATree.TestIsGraphATree(); ReverseGraph.TestReverseGraph(); StronglyConnectedGraph.TestStronglyConnectedGraph(); ConnectedComponents.TestConnectedComponents(); ContinentalDivide.TestContinentalDivide(); CloneGraph.TestCloneGraph(); Wordament.TestWordament(); // ShortestPathAlgo FloydWarshall.TestFloydWarshall(); DijkstraAlgorithm.TestDijkstraAlgorithm(); BellmanFord.TestBellmanFord(); TravelFromLeftToRightInMatrix.TestTravelFromLeftToRightInMatrix(); HeuristicSearch.TestHeuristicSearch(); AStar.TestAStar(); ShortestPathWhenObstaclesRemoved.TestShortestPathWhenObstaclesRemoved(); ShortestDistanceFromRoomsToGates.TestShortestDistanceFromRoomsToGates(); //MaxFlow FordFulkersonEdmondKarp.TestFordFulkersonEdmondKarp(); MinCut.TestMinCut(); MaximumBipartiteMatching.TestMaximumBipartiteMatching(); //Minimum Spanning Tree KruskalAlgorithm.TestKruskalAlgorithm(); PrimsAlgorithm.TestPrimsAlgorithm(); //Heap problems BasicMaxHeap.TestMaxHeap(); BasicMinHeap.TestMinHeap(); TestMinHeapMap.DoTest(); TestPriorityQueue.Run(); MedianForAStreamOfNumbers.TestMedianForAStreamOfNumbers(); //DisjointSets TestingDisjointSet.Run(); //TestWeightedDisjointSetsWithPathCompression.Run(); // this runs slow, hence commenting it //Geometry ClosestPairOfPoints.TestClosestPairOfPoints(); RectangleIntersection.TestRectangleIntersection(); LineSegmentIntersection.TestLineSegmentIntersection(); ConvexHull.TestConvexHull(); KClosestPointToOrigin.TestKClosestPointToOrigin(); //Greedy Algorithm HuffmanCoding.TestHuffmanCoding(); //Randomized Algorithm RandomGeneration.TestRandomGeneration(); // Bit Algorithms IntHaveOppositeSigns.TestIntHaveOppositeSigns(); Parity.TestParity(); //Math Problem ZerosInFactorial.TestZerosInFactorial(); GetAllPrimeFactors.TestGetAllPrimeFactors(); NumberOfFactors.TestNumberOfFactors(); AllFactors.TestAllFactors(); MultiplyLongNumbers.TestMultiplyLongNumbers(); NextLargestPermutation.TestNextLargestPermutation(); AllPrimesTillN.TestAllPrimesTillN(); PascalsTriangle.TestPascalsTriangle(); SubtractLongNumbers.TestSubtractLongNumbers(); //Search problems SearchInSortedRotatedArray.TestSearchInSortedRotatedArray(); KClosestElementInArray.TestKClosestElementInArray(); SearchInSortedMatrix.TestSearchInSortedMatrix(); BinarySearchUnbounded.TestBinarySearchUnbounded(); LinkedListSublistSearch.TestLinkedListSublistSearch(); NoOfOccuranceInSortedArray.TestNoOfOccuranceInSortedArray(); GetSmallestInSortedRotatedArray.TestGetSmallestInSortedRotatedArray(); //Distributed algorithms KWayMerge.TestKWayMerge(); Console.ReadLine(); }