Esempio n. 1
0
        static void Main(string[] args)
        {
            Search             search    = new Search();
            Student            root      = search.LoadStudentGraph();
            DijkstrasAlgorithm shortPath = new DijkstrasAlgorithm();

            var userName = search.PromptUser();

            Student breadthSearchName = search.BreadthSearch(root, userName);

            Console.WriteLine();
            Console.WriteLine(breadthSearchName != null ? $"Your search returned the following result; Student ID: {breadthSearchName.Id}, Student Name: {breadthSearchName.Name}, GPA: {breadthSearchName.Gpa}" : $"No results were found for Student Name: {userName}");
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Depth First Search");
            Student depthSearchName = search.DepthSearch(root, userName);

            Console.WriteLine();
            Console.WriteLine(depthSearchName != null ? $"Your search returned the following result; Student ID: {depthSearchName.Id}, Student Name: {depthSearchName.Name}, GPA: {depthSearchName.Gpa}" : $"No results were found for Student Name: {userName}");
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Dijkstra's Algorithm Search");
            var graph = DijkstrasAlgorithm.GenerateGraph();

            shortPath.FindShortestPath(graph, 0, 20);
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
            Console.Clear();
            Console.WriteLine("The End.");
            Console.ReadLine();
        }
        public void DijkstrasSinglePathAlgorithmExecuteTest()
        {
            Func <IGraphEdge, Double> weightFunction = edge => Convert.ToDouble(edge["Weight"]);

            IDictionary <OperationParameter, Object> parameters = new Dictionary <OperationParameter, Object>();

            parameters[GraphOperationParameters.SourceVertex] = _sourceVertex;
            parameters[GraphOperationParameters.WeightMetric] = weightFunction;

            DijkstrasAlgorithm operation = new DijkstrasAlgorithm(_sourceGraph, parameters);

            operation.Execute();

            Assert.AreEqual(_resultGraph.VertexCount, operation.Result.VertexCount);
            Assert.AreEqual(_resultGraph.EdgeCount, operation.Result.EdgeCount);

            foreach (IGraphVertex resultVertex in operation.Result.Vertices)
            {
                IGraphVertex vertex = _resultGraph.GetVertex(resultVertex.Coordinate);

                Assert.IsNotNull(vertex);
                Assert.AreEqual(vertex["Distance"], resultVertex["Distance"]);

                Assert.IsTrue(operation.Result.OutEdges(resultVertex).All(edge => _resultGraph.GetAllEdges(edge.Source.Coordinate, edge.Target.Coordinate).Count == 1));
            }
        }
Esempio n. 3
0
        public void GetShortestPathTest()
        {
            //Arrange
            var nodes        = CreateNodeDictionary();
            var expectedPath = new List <string> {
                "A", "C", "E", "F"
            };
            const int expectedCost = 10;

            //Act
            var dijkstrasAlgorithm = new DijkstrasAlgorithm(nodes.Values, "A");
            var shortestPath       = dijkstrasAlgorithm.GetShortestPath("F");

            //LogAndAssert
            var actualPath         = shortestPath.Select(node => node.Id).ToList();
            var expectedPathString = string.Join(" -> ", expectedPath);
            var actualPathString   = string.Join(" -> ", actualPath);
            var actualCost         = shortestPath[shortestPath.Count - 1].Cost;

            Console.WriteLine($"expected -- Cost: {expectedCost} Path: {expectedPathString}");
            Console.WriteLine($"actual -- Cost: {actualCost} Path: {actualPathString}");
            Assert.AreEqual(expectedCost, actualCost);
            Assert.AreEqual(expectedPath.Count, actualPath.Count);
            Assert.IsTrue(expectedPath.Zip(actualPath, (e, a) => e == a).All(e => e));
        }
        private void Update()
        {
            nodesCount = nodes.Count;

            if (Input.GetKeyDown(KeyCode.Mouse0))
            {
                var nearestNode = Geometry.GetNearestNodeToMouseClickPos(Camera.main.ScreenToWorldPoint(Input.mousePosition), nodes);
                Debug.Log(nearestNode.transform.position);
                Debug.Log(nearestNode.name);
                var currentDestinationIndex = int.Parse(nearestNode.name.Split('-')[1]);
                Debug.Log(currentDestinationIndex);
                DijkstrasAlgorithm.dijkstra(gameGraph, sourceNodeIndex, currentDestinationIndex, currentSolutionList);
                Debug.Log("Solution: ");
                foreach (var el in currentSolutionList)
                {
                    Debug.Log(el);
                }

                for (int i = 0; i < currentSolutionList.Count - 1; i++)
                {
                    GameObject.Find(currentSolutionList[i].ToString() + "-" + currentSolutionList[i + 1].ToString()).GetComponent <LineRenderer>().material = greenLineMaterial;
                    GameObject.Find(currentSolutionList[i + 1].ToString() + "-" + currentSolutionList[i].ToString()).GetComponent <LineRenderer>().material = greenLineMaterial;
                }
            }
        }
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();
        DijkstrasAlgorithm DS = (DijkstrasAlgorithm)target;

        // Once set, the user will check the box (IsStartingPointSet). If true, then draw a sphere at that position
        DS.IsStartingPointSet = EditorGUILayout.Toggle("IsStartingPointSet", DS.IsStartingPointSet);
    }
Esempio n. 6
0
        public void DAFindShortestPath()
        {
            var graph = new Graph("C:\\Users\\SCOTT\\Desktop\\159201\\Assignments\\6\\graph5.txt");

            DijkstrasAlgorithm.FindShortestPath(graph, 'A');
            Console.WriteLine();
            var graph2 = new Graph("C:\\Users\\SCOTT\\Desktop\\159201\\Assignments\\6\\graph1.txt");

            DijkstrasAlgorithm.FindShortestPath(graph2, 'A');
            Console.WriteLine();
            DijkstrasAlgorithm.FindShortestPath(graph, 'N');
        }
Esempio n. 7
0
        public static void Main(string[] args)
        {
            var matrix = new AdjecencyMatrix <int?>(4, x => x.HasValue);

            matrix
            .From('A').To('B').Set(3).BiDirectional()
            .From('A').To('C').Set(1).BiDirectional()
            .From('A').To('D').Set(1).BiDirectional()
            .From('B').To('C').Set(3).BiDirectional()
            .From('B').To('D').Set(1).BiDirectional();

            var nodes = new DijkstrasAlgorithm().CreateShortestPathTree(matrix, 'A');
        }
Esempio n. 8
0
        public (int, List <T>) GetShortestPath(T source, T destination)
        {
            DijkstrasAlgorithm <T> .Run(GetNode(source));

            var distance    = GetNode(destination).DistanceFromSource;
            var path        = new List <T>();
            var currentNode = GetNode(destination);

            while (!currentNode.Value.Equals(source))
            {
                path.Add(currentNode.Value);
                currentNode = currentNode.PreviousNode;
            }
            path.Add(source);
            path.Reverse();
            return(distance, path);
        }
Esempio n. 9
0
        private void Start_Click(object sender, RoutedEventArgs e)
        {
            List <string> sourceCode = GetListStringFromRichTextBox(this.codeTextBox);

            ILexicalAnalyser analyser = new FiniteMachine(sourceCode);

            analyser.Analize();

            Const.AllConstFromCode = analyser.ConstantList;
            Idnt.AllIdnFromCode    = analyser.IdentifierList;
            if (showLexemTable.IsChecked)
            {
                new LexemTable(analyser.LexemList, analyser.IdentifierList, analyser.ConstantList).Show();
            }



            ISyntaxAnalyser syntaxAnalyser  = new AscendingAnalys();
            ISyntaxAnalyser syntaxAnalyser2 = new RecursiveDescent();


            AdapterFromOldToNewModel adapter = new AdapterFromOldToNewModel(analyser.LexemList, analyser.IdentifierList, analyser.ConstantList);


            //try
            //{

            syntaxAnalyser2.CheckSyntax(adapter.ModelLexemList);

            syntaxAnalyser.CheckSyntax(adapter.ModelLexemList);

            DijkstrasAlgorithm dijkstra = new DijkstrasAlgorithm();

            dijkstra.BuildRPN(adapter.ModelLexemList);
            ExecutingRPN.ExecutingRPN executingRPN = new ExecutingRPN.ExecutingRPN(dijkstra.OutputList);

            this.Activate();
            executingRPN.Execute();

            //}
            //    catch (Exception ex)
            //    {
            //        MessageBox.Show(ex.Message+" "+ex.Source);
            //    }
        }
Esempio n. 10
0
    IEnumerator TwitchHandleForcedSolve()
    {
        if (_marbleDist == 0 || _queue == null)
        {
            yield break; // already solved or bomb blew up
        }
        int totalWeight;
        var results = DijkstrasAlgorithm.Run(new DijNode(_rotations, _traps, _colorIxs, 5, -1), 0, (a, b) => a + b, out totalWeight);

        foreach (var result in results)
        {
            while ((int)Bomb.GetTime() % 10 != result)
            {
                yield return(true);
            }
            Selectable.OnInteract();
            yield return(new WaitForSeconds(.1f));
        }

        while (!_isSolved)
        {
            yield return(true);
        }
    }
Esempio n. 11
0
 public void TestInvalidVertex()
 {
     DijkstrasAlgorithm <int> .FindShortestPaths(new Graph <int>(true), new Vertex <int>(5));
 }
Esempio n. 12
0
 public void TestNullVertex()
 {
     DijkstrasAlgorithm <int> .FindShortestPaths(new Graph <int>(true), null);
 }
Esempio n. 13
0
 public void TestNullGraph()
 {
     DijkstrasAlgorithm <int> .FindShortestPaths(null, new Vertex <int>(5));
 }
Esempio n. 14
0
        public void MoreComplicatedDirectedGraph()
        {
            Graph <string> graph = new Graph <string>(true);


            Vertex <string> a = new Vertex <string>("a");
            Vertex <string> b = new Vertex <string>("b");
            Vertex <string> c = new Vertex <string>("c");
            Vertex <string> d = new Vertex <string>("d");
            Vertex <string> e = new Vertex <string>("e");
            Vertex <string> f = new Vertex <string>("f");
            Vertex <string> g = new Vertex <string>("g");

            graph.AddVertex(a);
            graph.AddVertex(b);
            graph.AddVertex(c);
            graph.AddVertex(d);
            graph.AddVertex(e);
            graph.AddVertex(f);
            graph.AddVertex(g);

            graph.AddEdge(a, f, 4);

            graph.AddEdge(b, a, 2);
            graph.AddEdge(b, g, 2);

            graph.AddEdge(c, b, 3);

            graph.AddEdge(d, c, 2);
            graph.AddEdge(d, e, 1);

            graph.AddEdge(e, f, 3);
            graph.AddEdge(e, g, 2);

            graph.AddEdge(f, g, 1);

            graph.AddEdge(g, f, 1);
            graph.AddEdge(g, d, 3);
            graph.AddEdge(g, c, 4);
            graph.AddEdge(g, a, 1);

            Graph <string> result = DijkstrasAlgorithm <string> .FindShortestPaths(graph, g);

            Assert.AreEqual(result.VertexCount, 7);
            Assert.AreEqual(result.EdgeCount, 6);

            List <Edge <string> > edges = new List <Edge <string> >();

            using (IEnumerator <Edge <string> > enumerator = result.Edges)
            {
                while (enumerator.MoveNext())
                {
                    edges.Add(enumerator.Current);
                }
            }

            for (int i = 0; i < edges.Count; i++)
            {
                if ((edges[i].FromVertex.Data == "g") && (edges[i].ToVertex.Data == "a"))
                {
                    Assert.AreEqual(edges[i].Weight, 1);
                    Assert.AreEqual(edges[i].FromVertex.Weight, 0);
                    Assert.AreEqual(edges[i].ToVertex.Weight, 1);
                }
                else if ((edges[i].FromVertex.Data == "c") && (edges[i].ToVertex.Data == "b"))
                {
                    Assert.AreEqual(edges[i].Weight, 3);
                    Assert.AreEqual(edges[i].FromVertex.Weight, 4);
                    Assert.AreEqual(edges[i].ToVertex.Weight, 7);
                }
                else if ((edges[i].FromVertex.Data == "g") && (edges[i].ToVertex.Data == "c"))
                {
                    Assert.AreEqual(edges[i].Weight, 4);
                    Assert.AreEqual(edges[i].FromVertex.Weight, 0);
                    Assert.AreEqual(edges[i].ToVertex.Weight, 4);
                }
                else if ((edges[i].FromVertex.Data == "g") && (edges[i].ToVertex.Data == "d"))
                {
                    Assert.AreEqual(edges[i].Weight, 3);
                    Assert.AreEqual(edges[i].FromVertex.Weight, 0);
                    Assert.AreEqual(edges[i].ToVertex.Weight, 3);
                }
                else if ((edges[i].FromVertex.Data == "d") && (edges[i].ToVertex.Data == "e"))
                {
                    Assert.AreEqual(edges[i].Weight, 1);
                    Assert.AreEqual(edges[i].FromVertex.Weight, 3);
                    Assert.AreEqual(edges[i].ToVertex.Weight, 4);
                }
                else if ((edges[i].FromVertex.Data == "g") && (edges[i].ToVertex.Data == "f"))
                {
                    Assert.AreEqual(edges[i].Weight, 1);
                    Assert.AreEqual(edges[i].FromVertex.Weight, 0);
                    Assert.AreEqual(edges[i].ToVertex.Weight, 1);
                }
                else
                {
                    throw new Exception("Incorrect edge found for shortest path.");
                }
            }
        }
Esempio n. 15
0
        public static void Solver()
        {
            var colors = getStrArr("Colors? ");

            if (colors == null)
            {
                return;
            }
            var colorNames = "red,yellow,green,blue,silver".Split(',');

            if (colors.Any(c => !colorNames.Any(cn => cn.EqualsNoCase(c))))
            {
                return;
            }
            var colorIxs = colors.Select(c => colorNames.IndexOf(c, StringComparer.InvariantCultureIgnoreCase)).Reverse().ToArray();
            var gaps     = getIntArr("Gaps? ");

            if (gaps == null)
            {
                return;
            }
            var traps = getIntArr("Traps? ");

            if (traps == null)
            {
                return;
            }

            try
            {
                var result = DijkstrasAlgorithm.Run(new DijNode(gaps.Reverse().ToArray(), gaps.Zip(traps, (g, t) => t - g).Reverse().ToArray(), colorIxs, 5, -1), 0, (a, b) => a + b, out var totalWeight);
                Console.WriteLine(result.JoinString("\n"));
                Console.WriteLine($"Total weight: {totalWeight}");
            }
            catch (DijkstraNoSolutionException <int, string> e)
            {
                Console.WriteLine("No solution found.");
                var all = new HashSet <string>();
                for (int a = 0; a < 10; a++)
                {
                    for (int b = 0; b < 10; b++)
                    {
                        for (int c = 0; c < 10; c++)
                        {
                            for (int d = 0; d < 10; d++)
                            {
                                for (int f = 0; f < 10; f++)
                                {
                                    all.Add($"{a},{b},{c},{d},{f}");
                                }
                            }
                        }
                    }
                }
                foreach (DijNode elem in e.HashSet)
                {
                    if (!all.Remove(elem.Rotations.Select(r => (r % 10 + 10) % 10).JoinString(",")))
                    {
                        System.Diagnostics.Debugger.Break();
                    }
                    if (elem.Rotations.All(r => (r % 10 + 10) % 10 == 0) || elem.Marble != 5)
                    {
                        Console.WriteLine(elem);
                    }
                }
                Console.WriteLine($"Remaining:\n{all.JoinString("\n")}");
                System.Diagnostics.Debugger.Break();
            }
        }
Esempio n. 16
0
    void LevelGenerator(int seed)
    {
        var rnd = new System.Random(seed);
        int unusedVariable;

startOver:
        var validStates = new List <GameState>();

        for (var x = 0; x < cols; x++)
        {
            for (var y = 0; y < rows; y++)
            {
                foreach (var or in new[] { Orientation.Horiz, Orientation.Vert, Orientation.Upright })
                {
                    var state = new GameState {
                        curPosX = x, curPosY = y, orientation = or
                    };
                    if (!state.DeservesStrike(validPositions, cols))
                    {
                        validStates.Add(state);
                    }
                }
            }
        }

        var checkPoints = new List <GameState>();
        var startChPtIx = rnd.Next(0, validStates.Count);

        checkPoints.Add(validStates[startChPtIx]);
        validStates.RemoveAt(startChPtIx);
        var newGrid = new char[validPositions.Length];

        for (var i = 0; i < newGrid.Length; i++)
        {
            newGrid[i] = '-';
        }

        for (var i = 1; i < numCheckPoints; i++)
        {
tryAgain:
            var ix = rnd.Next(0, validStates.Count);
            if (i == numCheckPoints - 1 && validStates[ix].orientation != Orientation.Upright)
            {
                goto tryAgain;
            }
            if (i > 0 && ManhattanDistance(checkPoints.Last(), validStates[ix]) < 7)
            {
                goto tryAgain;
            }
            var nextCheckPoint = validStates[ix];

            try
            {
                var node = new BloxxNode {
                    ValidStates = new HashSet <GameState>(validStates), GameState = checkPoints.Last(), DesiredEndState = nextCheckPoint
                };
                var path = DijkstrasAlgorithm.Run(node, 0, (a, b) => a + b, out unusedVariable);
                foreach (var tup in path)
                {
                    tup.State.MarkUsed(newGrid, cols);
                    validStates.Remove(tup.State);
                }
                checkPoints.Add(nextCheckPoint);
            }
            catch (DijkstraNoSolutionException <int, PathElement> )
            {
                goto startOver;
            }
            validStates.Remove(nextCheckPoint);
        }

        // Find shortest path
        var overallStart = new BloxxNode {
            GameState = checkPoints[0], DesiredEndState = checkPoints.Last(), ValidPositions = new string(newGrid), ValidPositionsWidth = cols
        };
        var shortestPath = DijkstrasAlgorithm.Run(overallStart, 0, (a, b) => a + b, out unusedVariable).ToArray();

        var finalGrid = new char[validPositions.Length];

        for (var i = 0; i < finalGrid.Length; i++)
        {
            finalGrid[i] = '-';
        }
        // Mark reachable squares
        for (var spIx = 0; spIx < shortestPath.Length; spIx++)
        {
            shortestPath[spIx].State.MarkUsed(finalGrid, cols, spIx == shortestPath.Length - 1 ? 'X' : '#');
        }
        // Mark start and end location
        checkPoints[0].MarkUsed(finalGrid, cols, checkPoints[0].posChar());
        checkPoints.Last().MarkUsed(finalGrid, cols, 'X');
        if (finalGrid.Count(ch => ch == '#') < 40)
        {
            goto startOver;
        }

        state       = checkPoints[0];
        grid        = new string(finalGrid);
        solution    = shortestPath;
        threadReady = true;
    }