Exemple #1
0
        private void btnChayTuDong_Click(object sender, EventArgs e)
        {
            if (Check())
            {
                // kiểm tra time delay
                int timeDelay = 0;
                try
                {
                    timeDelay = Int32.Parse(txtDelay.Text);
                    if (timeDelay < 0)
                    {
                        MessageBox.Show("Time delay phải là số nguyên dương", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                catch
                {
                    MessageBox.Show("Time delay phải là số nguyên dương","Thông báo",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    return;
                }

                btnTamDung.Enabled = true;
                btnKetThuc.Enabled = true;
                btnBatDauChayTungBuoc.Enabled = false;
                groupSetting.Enabled = false;

                listDoThi = DFS.Run(Data.Data.graph_DFS, (int)cbxDinhXuatPhat.SelectedValue, (int) cbxDinhKetThuc.SelectedValue);
                index = 0;
                timer.Enabled = true;
                timer.Interval = timeDelay;
                timer.Start();
                return;
            }
        }
Exemple #2
0
        private void btnBatDauChayTungBuoc_Click(object sender, EventArgs e)
        {
            if (btnBatDauChayTungBuoc.Text == "Bắt đầu chạy từng bước")
            {
                if (Check())
                {
                    listDoThi = DFS.Run(Data.Data.graph_DFS, (int)cbxDinhXuatPhat.SelectedValue, (int)cbxDinhKetThuc.SelectedValue);
                    index = 0;
                    HienThiDoThi();

                    btnChayTuDong.Enabled = false;
                    btnPrev.Enabled = true;
                    btnNext.Enabled = true;
                    btnStart.Enabled = true;
                    btnEnd.Enabled = true;
                    groupSetting.Enabled = false;
                    btnBatDauChayTungBuoc.Text = "Kết thúc chạy từng bước";
                }
                return;
            }

            if (btnBatDauChayTungBuoc.Text == "Kết thúc chạy từng bước")
            {
                btnBatDauChayTungBuoc.Text = "Bắt đầu chạy từng bước";
                btnChayTuDong.Enabled = true;
                btnPrev.Enabled = false;
                btnNext.Enabled = false;
                btnStart.Enabled = false;
                btnEnd.Enabled = false;
                groupSetting.Enabled = true;
                return;
            }
        }
Exemple #3
0
        static void Main()
        {
            Console.WriteAscii("Light up solver", Color.Yellow);
            Console.WriteLine("Authors: Michał Bator, Agnieszka Sobota", Color.LightYellow);
            Console.WriteLine();

            Console.WriteLine("Starting session:");

            Console.WriteLine("Provide a path to the board file: ");
            var path = Console.ReadLine();


            if (!File.Exists(path))
            {
                Console.WriteLine("Provided path does not lead to any file. Exiting.", Color.Red);
                Console.ReadKey();
                return;
            }

            var board = new Board(path);

            Console.WriteLine("====================================");
            Console.WriteLine();
            Console.WriteLine("\tBoard loaded successfully.");
            Console.WriteLine();

            var DFSbox   = new DFS(board);
            var AStarBox = new AStar(board);

            Task.Run(() => DFSbox.Perform());
            Task.Run(() => AStarBox.Perform());


            Console.ReadKey();
        }
Exemple #4
0
        static void Main()
        {
            var n1  = new Node("n1");
            var n2  = new Node("n2");
            var n3  = new Node("n3");
            var n4  = new Node("n4");
            var n5  = new Node("n5");
            var n6  = new Node("n6");
            var n7  = new Node("n7");
            var n8  = new Node("n8");
            var n9  = new Node("n9");
            var n10 = new Node("n10");

            n1.AddChildren(n2).AddChildren(n3).AddChildren(n4);

            n2.AddChildren(n5);
            n3.AddChildren(n5);
            n4.AddChildren(n6);
            n5.AddChildren(n7);

            n6.AddChildren(n8);
            n6.AddChildren(n9);

            n7.AddChildren(n10);
            n8.AddChildren(n10);
            n9.AddChildren(n10);

            var fullPath = DFS.FindFullPath(n6, n10);

            foreach (var item in fullPath)
            {
                Console.Write($"{item.Name} ");
            }
            Console.ReadKey();
        }
Exemple #5
0
    void SetTarget_Local(MapManager.NavPoint point)
    {
        moveRode = null;
        objSign.SetActive(true);
        objSign.transform.position = new Vector3(point.col, 0, point.row);
        System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
        stopWatch.Start();
        switch (navType)
        {
        case NavLibrary.Algorithm.DFS:
            moveRode = DFS.Navigation(currentPoint, point);
            break;

        case NavLibrary.Algorithm.BFS:
            moveRode = BFS.Navigation(currentPoint, point);
            break;

        case NavLibrary.Algorithm.A_Star:
            moveRode = A_Star.Navigation(currentPoint, point);
            break;

        default:
            moveRode = null;
            break;
        }
        stopWatch.Stop();
        MainView.Instance.RefreshInfo(point.row, point.col, stopWatch.Elapsed.TotalMilliseconds);
        Debug.Log("Cost Time: " + stopWatch.Elapsed.TotalMilliseconds);
        if (!IsMoving)
        {
            MoveToNextPoint_Local();
        }
    }
        private void CreateWall(Wall wallEntity)
        {
            Wall randomWall;

            if (wallEntity.Row >= 0 && wallEntity.Column >= 0)
            {
                randomWall = wallEntity;
            }
            else
            {
                var notActiveWalls = GetNotActiveWalls();

                var availableWalls = notActiveWalls.Where((wall) => {
                    var wallsOnPosition = GetWallsOnPosition(wall.Row, wall.Column);

                    var nextPos             = PositionHelper.GetNextPosition(wall.Row, wall.Column, wall.Direction);
                    var wallsOnNextPosition = GetWallsOnPosition(nextPos.Row, nextPos.Column);

                    return(wallsOnPosition.Count < 2 && wallsOnNextPosition.Count < 2 &&
                           DFS.IsConnectedWithoutEdge(_graph, wall.Row, wall.Column, nextPos.Row, nextPos.Column));
                }).ToList();

                randomWall = availableWalls.RandomElement();
            }
            if (randomWall == null)
            {
                return;
            }

            CloseWall(wallEntity, randomWall);

            var nextPosition = PositionHelper.GetNextPosition(randomWall.Row, randomWall.Column, randomWall.Direction);

            _graph.RemoveEdge(randomWall.Row, randomWall.Column, nextPosition.Row, nextPosition.Column);
        }
Exemple #7
0
        public static void Main(string[] args)
        {
            var dfs = new DFS();

            dfs.TestDFS();
            // var bfs = new BFS();
            // bfs.TestBFS();

            // var fibo = new Fibonacci();
            // fibo.TestFibonacci();

            // var floodFill = new FloodFill();
            // floodFill.TestFloodFillDFS();
            // floodFill.TestGraphTraversalBlockedSpacesAnd4MovesDFS();
            // floodFill.TestShortestPathTraversal();

            var greedy = new GreedyAlgo();

            // greedy.ComputeMaxTasksCompleted();
            greedy.ComputeMaxPrioritizedTasksCompleted();

            // DicesSumModel diceSumModel = new DicesSumModel();
            // diceSumModel.TestProbabilityDiceSum();

            // DateTimeModel dateTimeModel = new DateTimeModel();
            // dateTimeModel.TestMultipleDateTimeDiff();

            // Build webhost
            // BuildWebHost(args).Run();
        }
Exemple #8
0
        /// <summary>
        /// Compares the solvers.
        /// </summary>
        /// <param name="row">The row.</param>
        /// <param name="col">The col.</param>
        public static void CompareSolvers(int row, int col)
        {
            // create maze
            DFSMazeGenerator myMazeGen = new DFSMazeGenerator();
            Maze             maze      = myMazeGen.Generate(row, col);

            Console.WriteLine(maze);
            ObjectAdapter mazeAdapter = new ObjectAdapter(maze);

            // BFS solution
            ISearcher <Position> sbfs = new BFS <Position>();

            sbfs.Search(mazeAdapter);

            // print num of stages
            Console.WriteLine("BFS: " + sbfs.GetNumberOfNodesEvaluated());

            // DFS solution
            ISearcher <Position> sdfs = new DFS <Position>();

            sdfs.Search(mazeAdapter);

            // print num of stages
            Console.WriteLine("DFS: " + sdfs.GetNumberOfNodesEvaluated());
        }
Exemple #9
0
        /// <summary>
        /// Generates a thread that solves the maze 'mazeName'
        /// </summary>
        /// <param name="mazeName">maze name</param>
        /// <param name="algorithm">algorithm to solve with</param>
        public void solveMaze(string mazeName, string algorithm)
        {
            ISearchingAlgorithm searching = null;

            if ("BFS" == algorithm)
            {
                searching = new BFS();
            }

            else if ("DFS" == algorithm)
            {
                searching = new DFS();
            }

            else
            {
                m_controller.errOutput("wrong argument inserted for <algorithm>, Algorithm options are BFS/DFS\n");
                return;
            }
            m_controller.Output("Solving maze...\n");
            Thread thread = new Thread(() => solve(searching, mazeName));

            m_threads.Add(thread);
            thread.Start();
        }
Exemple #10
0
 private void buttonRecomen_Click(object sender, EventArgs e)
 {
     if (dropdownRecommend.Text != "")
     {
         Node person = Parser.result.persons.Find(p => p.name.Equals(dropdownRecommend.Text));
         if (this.DFSbuttonRekomen.Checked)
         {
             string rekomen = DFS.friendRecommendation(Parser.result, person);
             this.textRecomens.Text = rekomen;
         }
         else if (this.BFSbuttonRekomen.Checked)
         {
             string rekomen = BFS.friendRecommendation(Parser.result, person);
             this.textRecomens.Text = rekomen;
         }
         else
         {
             this.textRecomens.Text = "";
             MessageBox.Show("Anda harus memilih algoritma pencarian");
         }
     }
     else
     {
         MessageBox.Show("Anda harus mengisi dropdown");
     }
 }
Exemple #11
0
        public SolutionDetails <Direction> SolveMaze(string name, int algo)
        {
            SolutionDetails <Direction>    sol_det;
            Searcher <Position, Direction> s;

            if (Sol.TryGetValue(name, out sol_det))
            {
                return(sol_det);
            }
            Maze maze;

            Mazes.TryGetValue(name, out maze);
            if (maze == null)
            {
                return(null);
            }
            if (algo == BFS)
            {
                s = new BestFS();
            }
            else
            {
                s = new DFS();
            }

            sol_det = s.search(new SearchableMaze(maze));
            //sol_det = new SolutionDetails<Direction>(s.search(new SearchableMaze(maze)), s.getNumberOfNodesEvaluated());
            Sol.Add(name, sol_det);
            return(sol_det);
        }
Exemple #12
0
        private static void DisplayEdgeProperties <T>(Graph <T> graph) where T : IComparable <T>
        {
            DFS <T> dfs = new DFS <T>(graph);

            dfs.EdgeTraversed += new EventHandler <EdgeEventArgs <T> >(GraphEventFunctions.DisplayEdgeProperties);
            dfs.Compute();
        }
Exemple #13
0
        /// <summary>
        /// solving a private maze
        /// if the solution for this maze already exists it returns it
        /// </summary>
        /// <param name="name"></param>
        /// <param name="algorithm"></param>
        /// <returns></returns>
        public string SolveMaze(string name, int algorithm)
        {
            Maze m = privateMazeDict[name];
            MazeAdapter <Position> maze = new MazeAdapter <Position>(m);
            Searcher <Position>    searcher;
            Solution <Position>    sol;

            if (!privateSolDict.Keys.Contains(name))
            {
                if (algorithm == 0)
                {
                    searcher = new BFS <Position>();
                    CostComparator <Position> compare = new CostComparator <Position>();
                    sol = searcher.Search(maze, compare);
                }
                else
                {
                    searcher = new DFS <Position>();
                    sol      = searcher.Search(maze);
                }

                privateSolDict.Add(name, sol);
            }
            else
            {
                sol = privateSolDict[name];
            }

            string stringSolution         = maze.ToSolution(sol);
            int    numberOfNodesevaluated = sol.EvaluatedNodes;

            stringSolution += " ";
            stringSolution += numberOfNodesevaluated;
            return(stringSolution);
        }
Exemple #14
0
        public void Test_Search()
        {
            // arrange
            var root  = new Node(0);
            var one   = new Node(1);
            var two   = new Node(2);
            var three = new Node(3);
            var four  = new Node(4);
            var five  = new Node(5);

            root.Children.Add(one);
            root.Children.Add(four);
            root.Children.Add(five);

            one.Children.Add(four);
            one.Children.Add(three);

            three.Children.Add(four);
            three.Children.Add(two);

            two.Children.Add(one);
            // act
            var actual = new DFS().Search(root, new List <int>());

            // assert
            var expected = new List <int> {
                0, 1, 4, 3, 2, 5
            };

            Assert.That(actual, Is.EqualTo(expected));
        }
Exemple #15
0
 public override void Update()
 {
     if (Input.KeyPressed(Key.D))
     {
         var search = new DFS <NearbyTiles, MoveAction>(_graphSearch);
         Game.SwitchScene(new LabyrinthScene <NearbyTiles, MoveAction>(_problem, search, _graphSearch));
     }
     else if (Input.KeyPressed(Key.B))
     {
         var graphSearchBFS = new GraphSearchBFS <NearbyTiles, MoveAction>();
         var search         = new BFS <NearbyTiles, MoveAction>(graphSearchBFS);
         Game.SwitchScene(new LabyrinthScene <NearbyTiles, MoveAction>(_problem, search, graphSearchBFS));
     }
     else if (Input.KeyPressed(Key.G))
     {
         var search = new GreedySearch <NearbyTiles, MoveAction>(_graphSearch,
                                                                 node => Math.Abs(21 - node.State.Center.X) + Math.Abs(20 - node.State.Center.Y));
         Game.SwitchScene(new LabyrinthScene <NearbyTiles, MoveAction>(_problem, search, _graphSearch));
     }
     else if (Input.KeyPressed(Key.A))
     {
         var search = new AStarSearch <NearbyTiles, MoveAction>(_graphSearch,
                                                                node => Math.Abs(21 - node.State.Center.X) + Math.Abs(20 - node.State.Center.Y));
         Game.SwitchScene(new LabyrinthScene <NearbyTiles, MoveAction>(_problem, search, _graphSearch));
     }
 }
Exemple #16
0
        /// <summary>
        /// Solves the maze.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="algorithm">The algorithm.</param>
        /// <returns></returns>
        public /*Solution<Position>*/ List <string> SolveMaze(string name, int algorithm)
        {
            SingleGame game = cash.GetSingleGame(name);

            if (game != null)
            {
                //Solution<Position> solution = cash.GetSolution(name);

                /*Solution<Position> solution = game.Solution;
                 * if (!(solution == null))
                 * {
                 *  return solution;
                 * }*/
                //Maze maze = cash.GetMaze(name);
                Maze maze = game.Maze;
                ISearcher <Position> searcher = null;

                if (algorithm == 0)
                {
                    searcher = new BFS <Position>();
                }
                else if (algorithm == 1)
                {
                    searcher = new DFS <Position>();
                }

                MazeAdapter <Position> mazeAdapter = new MazeAdapter <Position>(maze);
                Solution <Position>    solution    = searcher.Search(mazeAdapter);
                //cash.AddSolution(name, solution);
                //game.Solution = solution;
                return(this.GetSolutionString(solution.List));  //solution;
            }
            return(null);
        }
        /// <summary>
        /// Solves the maze.
        /// </summary>
        /// <param name="maze">The maze.</param>
        /// <returns>a list of mazePositions that represent the path
        /// that completed the given Maze
        /// </returns>
        internal List <MazePosition> SolveMaze(IMaze maze)
        {
            List <MazePosition>             solution = new List <MazePosition>();
            PathSearchResult <MazePosition> result;

            switch (this.way)
            {
            case WayToSolve.BFS:
                result = new BFS <MazePosition>().Search(new SearchableMaze(maze));
                break;

            case WayToSolve.DFS:
                result = new DFS <MazePosition>().Search(new SearchableMaze(maze));
                break;

            default:
                return(null);
            }
            // from States List to MazePositions List
            for (int i = 0; i < result.GetPathLenght(); i++)
            {
                solution.Add(result[i].TState);
            }
            return(solution);
        }
        /// <summary>
        /// Solves the maze.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="typeAlgo">The type algo.</param>
        /// <returns></returns>
        public static SolveInfo SolveMaze(string name, string typeAlgo)
        {
            Maze                maze           = singleplayerMazeList[name];
            MazeAdapter         mazeSearchable = new MazeAdapter(maze); // Isearchable
            var                 temp           = new CompareStates <Position>();
            Solution <Position> solution       = null;
            int                 nodesEvaluated = 0;

            if (solutionsList.ContainsKey(maze))
            {
                return(solutionsList[maze]);
            }

            // find solution of the maze:
            switch (typeAlgo)
            {
            case "0":
                BFS <Position> bfs = new BFS <Position>(temp);
                solution       = bfs.Search(mazeSearchable);
                nodesEvaluated = bfs.GetNumberOfNodesEvaluated();
                break;

            case "1":
                DFS <Position> dfs = new DFS <Position>(temp);
                solution       = dfs.Search(mazeSearchable);
                nodesEvaluated = dfs.GetNumberOfNodesEvaluated();
                break;
            }
            SolveInfo solveInfo = new SolveInfo(nodesEvaluated, solution);

            // add the solution to the solutions dictionary
            solutionsList.Add(maze, solveInfo);
            return(solveInfo);
        }
Exemple #19
0
        /// <summary>
        /// Solve Maze - Solves the given maze with a given
        /// solving algorithm - BFS/DFS
        /// </summary>
        /// <param name="mazeName">Maze name</param>
        /// <param name="solvingAlgorithm">Solving algorithm - BFS/DFS</param>
        public void solveMaze(string mazeName, string solvingAlgorithm)
        {
            ISearchingAlgorithm searchingAlgorithm = null;

            if (solvingAlgorithm == "DFS")
            {
                searchingAlgorithm = new DFS();
            }
            else if (solvingAlgorithm == "BFS")
            {
                searchingAlgorithm = new BFS();
            }
            else
            {
                return;
            }

            var resetEvent = new ManualResetEvent(false);

            ThreadPool.QueueUserWorkItem(new WaitCallback((state) =>
            {
                solve(searchingAlgorithm, mazeName);
                resetEvent.Set();
            }));
            resetEvent.WaitOne();
        }
Exemple #20
0
        /// <summary>
        /// Solves the specified maze.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="typeOfSolve">The type of solve.</param>
        /// <returns>the solve of the maze</returns>
        /// <exception cref="System.Exception">This maze does not exist - " + name</exception>
        public MazeSolution Solve(string name, int typeOfSolve)
        {
            if (solutionMazes.ContainsKey(name))
            {
                return(solutionMazes[name]);
            }

            if (mazes.ContainsKey(name))
            {
                Maze maze = mazes[name];

                ObjectAdapter adapter = new ObjectAdapter(maze);

                BFS <Position, int> bfs = new BFS <Position, int>();
                DFS <Position, int> dfs = new DFS <Position, int>();
                switch (typeOfSolve)
                {
                case 0:
                    return(ConvertSolution(bfs.Search(adapter), maze.Name));

                case 1:
                    return(ConvertSolution(dfs.Search(adapter), maze.Name));

                default:
                    throw new Exception("This search type does not exist - " + typeOfSolve);
                }
            }
            throw new Exception("This maze does not exist - " + name);
        }
Exemple #21
0
        /// <summary>
        /// Compares BFS and DFS solvers.
        /// </summary>
        public static void CompareSolvers(Maze maze)
        {
            var searchableMaze = new MazeAdapter(maze);

            int dfsNodesEvaluated, bfsNodesEvaluated;
            Solution <Position> dfsSolution, bfsSolution;

            Searcher <Position> searcher = new BFS <Position>(new CostComperator <Position>());

            bfsSolution       = searcher.Search(searchableMaze);
            bfsNodesEvaluated = searcher.GetNumberOfNodesEvaluated();

            searcher          = new DFS <Position>();
            dfsSolution       = searcher.Search(searchableMaze);
            dfsNodesEvaluated = searcher.GetNumberOfNodesEvaluated();

            bool isBfsBetter = dfsNodesEvaluated > bfsNodesEvaluated;

            Console.WriteLine("Better solution was found by {0} ({1} vs. {2} nodes evaluated)",
                              isBfsBetter ? "BFS" : "DFS",
                              isBfsBetter ? bfsNodesEvaluated : dfsNodesEvaluated,
                              isBfsBetter ? dfsNodesEvaluated : bfsNodesEvaluated);

            var drawer = new MazeDrawer();

            drawer.DrawMaze(searchableMaze, isBfsBetter ? bfsSolution:dfsSolution);
        }
Exemple #22
0
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <param name="args">The arguments.</param>
        static void Main(string[] args)
        {
            //generate the maze.
            DFSMazeGenerator mazeGenerator = new DFSMazeGenerator();
            Maze             maze          = mazeGenerator.Generate(30, 30);
            //adapt the maze.
            SearchableMazeAdapter searchableMaze = new SearchableMazeAdapter(maze);

            //printing the maze.
            Console.Write(searchableMaze.MyMaze.ToString());

            Solution <Position> BFSSolution;
            Solution <Position> DFSSolution;

            //solving by BFS.
            ISearcher <Position> searcher = new BFS <Position>();

            BFSSolution      = searcher.Search(searchableMaze);
            BFSSolution.Name = searchableMaze.MyMaze.Name;
            searchableMaze.Clean();

            //solving by DFS.
            searcher         = new DFS <Position>();
            DFSSolution      = searcher.Search(searchableMaze);
            DFSSolution.Name = searchableMaze.MyMaze.Name;

            //printing the solutions.
            Console.WriteLine(BFSSolution.EvaluatedNodes);
            Console.WriteLine(DFSSolution.EvaluatedNodes);
        }
Exemple #23
0
        static void Main(string[] args)
        {
            Console.WriteLine("----------------------START ALGORITHM TESTS----------------------");

            SelectionSort.RunTests();
            InsertionSort.RunTests();
            Factorial.RunTests();
            Palindrome.RunTests();
            Recursion.RunTests();
            MergeSort.RunTests();
            QuickSort.RunTests();
            BreadthFirstSearch.RunTests();

            Console.WriteLine("----------------------END ALGORITHM TESTS----------------------");
            Console.WriteLine("----------------------START PATTERN TESTS----------------------");

            BFS.RunTests();
            DFS.RunTests();
            SlidingWindow.RunTests();
            TwoPointers.RunTests();

            FastSlowPointers.RunTests();
            MergeIntervals.RunTests();

            Console.WriteLine("----------------------END PATTERN TESTS----------------------");
        }
Exemple #24
0
        private static void AddFilterToEdge <T>(Graph <T> G) where T : IComparable <T>
        {
            DFS <T> dfs = new DFS <T>(G);

            dfs.EdgeTraversed += new EventHandler <EdgeEventArgs <T> >(GraphEventFunctions.AddFilterToEdge <T>);
            dfs.Compute();
        }
Exemple #25
0
        public IEnumerable <Route> Handle(Request request, IRouteProblem problem)
        {
            ISolver solver = null;

            if (request.Solver == "BFS")
            {
                solver = new BFS();
            }
            if (request.Solver == "DFS")
            {
                solver = new DFS();
            }
            if (request.Solver == "Dijkstra")
            {
                if (request.Problem == "Time")
                {
                    solver = new DijkstraTime();
                }
                if (request.Problem == "Cost")
                {
                    solver = new DijkstraCost();
                }
            }
            if (solver != null)
            {
                problem.Accept(solver);
                return(problem.Results);
            }
            Console.WriteLine("Pick Solver failed");
            return(null);
        }
Exemple #26
0
 public DFSAgent(List <string> log)
 {
     //Setup the DStar Search
     Plan = new Stack <Action>();
     Plan.Push(new Action());
     DSearch = new DFS(log);
 }
Exemple #27
0
        public ActionResult ShowRecom(RecoomendSuperclass.Percept percept)
        {
            c2T = new ConvertToText();
            TreeNode treeNode = c2T.RetrieveTree();

            accomodationSuper = new StudentAccomodationSuper();
            DFS dFS = new DFS();

            RecoomendSuperclass.Percept percepts = new RecoomendSuperclass.Percept();
            percepts.Incomegroup = percept.Incomegroup;
            percepts.area        = percept.area;


            List <string> recommendations = dFS.IterativeDeepeningSearch(treeNode, percepts, 3, 1);

            if (recommendations != null)
            {
                GetRecommendations(recommendations);
                //accomodationSuper.overalRecommendations = studentAccomodation;
                TempData["nullOverall"] = false;
            }
            else
            {
                TempData["nullOverall"] = true;
            }


            //List<string> recommendations_safety = dFS.IterativeDeepeningSearch(treeNode, percepts, 3, 2);
            //if (recommendations_safety != null)
            //{
            //    GetURecommendations(recommendations_safety);
            //    //accomodationSuper.basedOnSafety = studentAccomodation;
            //}
            //else
            //{

            //    TempData["nullSafety"] = true;
            //}

            List <string> recommendations_sentiment = dFS.IterativeDeepeningSearch(treeNode, percepts, 3, 3);

            if (recommendations_sentiment != null)
            {
                GetTRecommendations(recommendations_sentiment);
                // accomodationSuper.basedOnsentiment = studentAccomodation;

                TempData["nullSentiment"] = false;
            }
            else
            {
                TempData["nullSentiment"] = true;
            }

            if (accomodationSuper != null)
            {
                Session["RecommendationRating"] = accomodationSuper;
                return(RedirectToAction("ShowRecommendations", "Recommend"));
            }
            return(View());
        }
Exemple #28
0
        public void TestDFS()
        {
            // DFS constructor
            Console.WriteLine("\n========== Test: DFS ==========");
            var dfs = new DFS <string>();

            // FindPath() with tinyDG.txt
            Console.WriteLine("\n========== FindPath() with tinyDG.txt ==========");

            Console.WriteLine("\nGraph:");
            Digraph <int> intGraph = TestGraphLoader.LoadGraph(@"../../../StudyGroupFinder/Data/tinyDG.txt");

            Console.Write(intGraph);
            Console.WriteLine("Verify at http://algs4.cs.princeton.edu/42digraph/Digraph.java.html");

            Console.WriteLine("\nPaths:");
            var dfsInt = new DFS <int>();

            foreach (Node <int> node in intGraph.Nodes.Values)
            {
                Node <int> n = intGraph.Nodes["3"];
                // HACK: Add source-to-source path
                Path p = n == node ? new Path(node.ToString()) : dfsInt.FindPath(intGraph, n, n2 => intGraph.Nodes[n2.ToString()] == node);
                Console.WriteLine($"3 to {node.ToString()} ({p.Count - 1}):  " + p.ToString());
            }

            Console.WriteLine("Verify at http://algs4.cs.princeton.edu/42digraph/DepthFirstDirectedPaths.java.html");

            // TEST: Add more verified DFS test samples
        }
        /// <summary>
        /// Solves the specified maze.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="algorithm">The algorithm.</param>
        /// <returns>
        /// solves the maze and returns the solution
        /// </returns>
        /// <exception cref="System.Exception">Failed at Solve function in model class</exception>
        public Solution <Position> Solve(string name, Algorithm algorithm)
        {
            Solution <MazeLib.Position> sol;
            MazeAdapter mazeAdapter = new MazeAdapter(GenerateMazeModel.mazes[name]);

            // if the maze is exists
            switch (algorithm)
            {
            case Algorithm.BFS:
            {
                WeightForEdges <MazeLib.Position> we = new WeightsForShortestWay <MazeLib.Position>();
                ISearcher <Position> bfs             = new BFS <MazeLib.Position>(we);
                // solve the maze with bfs.
                sol = bfs.Search(mazeAdapter);
            }
            break;

            case Algorithm.DFS:
            {
                ISearcher <Position> dfs = new DFS <Position>();
                // solves the maze with dfs.
                sol = dfs.Search(mazeAdapter);
            } break;

            default:
                return(null);
            }
            return(sol);
        }
        /**
         * 无向图测试
         */
        private void TestCycleGraph()
        {
            DFS  dfs = new DFS();
            Node a   = new Node("A");
            Node b   = new Node("B");
            Node c   = new Node("C");
            Node d   = new Node("D");
            Node e   = new Node("E");
            Node f   = new Node("F");
            Node g   = new Node("G");
            Node h   = new Node("H");

            dfs.AddTwoWayNodes(a, b);
            dfs.AddTwoWayNodes(b, c);
            dfs.AddTwoWayNodes(c, d);
            dfs.AddTwoWayNodes(d, a);
            dfs.AddTwoWayNodes(d, g);
            dfs.AddTwoWayNodes(a, e);
            dfs.AddTwoWayNodes(e, b);
            dfs.AddTwoWayNodes(a, f);
            dfs.AddTwoWayNodes(b, f);
            dfs.AddTwoWayNodes(b, h);
            dfs.SetHeadNode(a);
            dfs.FindCycles();
        }
Exemple #31
0
        public void TestGraphAlgorithms()
        {
            var bfs = new BFS<char>(_graph);
            var path1 = bfs.GetPath('A', 'E');
            CollectionAssert.AreEqual(path1, new char[] { 'A', 'D', 'E' });

            var dfs = new DFS<char>(_graph);
            var path2 = dfs.GetPath('A', 'E');
            CollectionAssert.AreEqual(path2, new char[] { 'A', 'D', 'E' });
        }
Exemple #32
0
    // Use this for initialization
    void Start()
    {
        gc = GameObject.FindWithTag("GameController").GetComponent<GameController>();
        //cache this for later
        firstPoint = startPoint.startingNavPoint;
        dfs = new DFS(firstPoint);
        //pops the top off the stack which is just the first point
        nextPoint = dfs.GetNextNavPoint();
        //put us at the start point if we're not
        if (Vector3.Distance(transform.position, nextPoint.position) > 0.05f)
            transform.position = nextPoint.position;
        //find our actual next point
        nextPoint = dfs.GetNextNavPoint();

        agent = GetComponent<NavMeshAgent>();
        agent.updateRotation = false;
        SetDestination(nextPoint.position);
        foundTribute = false;
    }
Exemple #33
0
    static void Main(string[] args)
    {
        string[] inputs;
        inputs = Console.ReadLine().Split(' ');
        int W = int.Parse(inputs[0]); // number of columns.
        int H = int.Parse(inputs[1]); // number of rows.
        var map = new List<int[]>();
        for (int i = 0; i < H; i++)
        {
            string LINE = Console.ReadLine(); // represents a line in the grid and contains W integers. Each integer represents one room of a given type.
            map.Add(LINE.Split(' ').Select(x => int.Parse(x)).ToArray());
        }
        int EX = int.Parse(Console.ReadLine()); // the coordinate along the X axis of the exit (not useful for this first mission, but must be read).
        var exit = new Point(EX, H-1, Direction.TOP);

        var dfs = new DFS(map);
        // game loop
        while (true)
        {
            inputs = Console.ReadLine().Split(' ');
            int XI = int.Parse(inputs[0]);
            int YI = int.Parse(inputs[1]);
            string POSI = inputs[2];
            var indy = new Point(XI, YI, directionOf(POSI));

            int R = int.Parse(Console.ReadLine()); // the number of rocks currently in the grid.
            var rocks = new Point[R];
            for (int i = 0; i < R; i++)
            {
                inputs = Console.ReadLine().Split(' ');
                int XR = int.Parse(inputs[0]);
                int YR = int.Parse(inputs[1]);
                string POSR = inputs[2];
                rocks[i] = new Point(XR, YR, directionOf(POSR));
            }

            //TODO: Add rocks to DFS
            Console.Error.WriteLine("Indy is at " + indy + " from the " + indy.Position + " which is tile #" + dfs.RoomTypeAt(indy));
            var path = dfs.To(indy, exit, rocks);

            Console.WriteLine(path);

            if (path != "WAIT")
            {
                var s = path.Split(' ');
                var pos = new Point(int.Parse(s[0]), int.Parse(s[1]), directionOf(s[2]));

                var oldType = dfs.RoomTypeAt(pos);
                dfs.Rotate(pos, 4 - (int)pos.Position);
                Console.Error.WriteLine("Storing change of tile at " + pos + " from a #" + oldType + " to a #" + dfs.RoomTypeAt(pos));
            }
            else
            {
                Console.Error.WriteLine("Indy waited");
            }
        }
    }