示例#1
0
 /// <summary>
 /// 获取DFS内容
 /// </summary>
 /// <param name="dfsPath"></param>
 /// <returns></returns>
 public static byte[] GetDataFromDfsPath(string dfsPath)
 {
     try
     {
         if (string.IsNullOrEmpty(dfsPath))
         {
             return(null);
         }
         var    item = Dfs.Get(dfsPath);
         byte[] data = null;
         int    i    = 0;
         while (i < 5)
         {
             data = GetDataFromDfsItem(item);
             if (data != null)
             {
                 return(data);
             }
             else
             {
                 i++;
                 Thread.Sleep(300);
             }
         }
         return(data);
     }
     catch (Exception err)
     {
         AppConnectLogHelper.Error(string.Format("DfsHelper.GetDataFromDfsPath failed, dfsPaht:{0}, exception{1}", dfsPath, err));
         return(null);
     }
 }
示例#2
0
        /// <summary>
        /// Function Compares Bfs and Dfs algorithm functions.
        /// </summary>
        public void CompareSolvers()
        {
            IMazeGenerator dfsMaze = new DFSMazeGenerator();


            // Print the maze.
            //Console.WriteLine(dfsMaze.ToString());
            StatePool <Position> spDfs = new StatePool <Position>();
            //Adapter adDfs = new Adapter(2, 2, 0, 0, 1, 1, "test Dfs", spDfs);
            Maze maze = dfsMaze.Generate(500, 500);

            Console.WriteLine(maze.ToString());
            Adapter adDfs               = new Adapter(maze, spDfs);
            ISearcher <Position> dfs    = new Dfs <Position>();
            Solution <Position>  solDfs = dfs.Search(adDfs);

            Console.WriteLine(Adapter.ToJson(solDfs, "test")); // Creates the solution in Json format.

            /*
             * StatePool<Position> spBfs = new StatePool<Position>();
             * // Adapter adBfs = new Adapter(10, 10, 0, 0, 8, 1, "test Bfs", spBfs);
             * Maze maze = dfsMaze.Generate(500, 500);
             * Console.WriteLine(maze.ToString());
             * Adapter adBfs = new Adapter(maze, spBfs);
             * ISearcher<Position> bfs = new Bfs<Position>();
             * Solution<Position> solBfs = bfs.search(adBfs);
             * //Console.WriteLine(adBfs.ToJson(solBfs));
             */
        }
        public string ExportExcelTemplate()
        {
            var tenantId = ApplicationContext.Current.TenantId;
            var userId   = ApplicationContext.Current.UserId;
            var path     = string.Empty;

            try
            {
                //设置Excel表头
                var templateData = AppAccountService.Instance.GetTemplateStream(tenantId, userId);
                if (templateData.Length == 0)
                {
                    //error
                    AppConnectLogHelper.Error("生成模板失败,文件数据流为null");
                    return(path);
                }
                var dfsItem = new DfsItem("AppConnectFile", "人员信息模板表.xls", templateData, tenantId);
                var dfsPath = Dfs.Store(dfsItem);
                path = Dfs.ToDownloadUrl(dfsPath.ToString(), UrlSignDomain.Tms, userId);

                ApplicationContext.Current.Put(Const.BeisenContextXHasException, ExceptionType.UrlRedirect);
                ApplicationContext.Current.Put(Const.BeisenContextXExResultModel, new ResultModel {
                    code = "302", message = "url redirect", param = path
                });
            }
            catch (Exception ex)
            {
                AppConnectLogHelper.Error("生成模板失败", ex);
            }
            return(path);
        }
示例#4
0
文件: MazeModle.cs 项目: mordehg/ex2
        /// <summary>
        /// solve the maze problem - singal player.
        /// </summary>
        /// <param name="name">maze name</param>
        /// <param name="algo">0-bfs, 1-dfs</param>
        /// <returns>get solution of maze problem</returns>
        public Solution <Position> Solve(string name, int algo)
        {
            if (this.mazesSinglePlayerPool.ContainsKey(name))
            {
                if (!this.solutionsSinglePlayerPool.ContainsKey(name))
                {
                    ISearcher <Position> searchAlgo;
                    Solution <Position>  solution;
                    Maze maze = this.mazesSinglePlayerPool[name];
                    Adapter <Position>     adapter        = new MazeToSearchableAdapter <Position>(maze);
                    ISearchable <Position> searchableMaze = new Searchable <Position, Direction>(adapter);
                    switch (algo)
                    {
                    case 0:
                        searchAlgo = new Bfs <Position>();
                        break;

                    case 1:
                        searchAlgo = new Dfs <Position>();
                        break;

                    default:
                        //Error at algorithem numeber: 0 - for bfs, 1 - for dfs
                        return(null);
                    }
                    solution = searchAlgo.Search(searchableMaze);
                    this.solutionsSinglePlayerPool.Add(name, solution);
                }
                return(this.solutionsSinglePlayerPool[name]);
            }
            //name of maze doesn't exist at maze single player pool"
            return(null);
        }
示例#5
0
        public static byte[] Read(string dfsPath)
        {
            var bytes = new byte[] { };

            try
            {
                var item = Dfs.Get(dfsPath);
                if (item != null)
                {
                    if (item.IsStream)
                    {
                        bytes = new byte[item.Length];
                        int index = 0;
                        while (index < item.Length)
                        {
                            int read = item.FileDataStream.Read(bytes, index, (int)(item.Length - index));
                            index += read;
                        }
                    }
                    else
                    {
                        bytes = item.FileDataBytes;
                    }
                }
            }
            catch (Exception err)
            {
                throw new Exception("读取dfs文件出错" + err.ToString());
            }

            return(bytes);
        }
示例#6
0
        static void Main(string[] args)
        {
            Dictionary <int, IList <int> > g = new Dictionary <int, IList <int> >
            {
                { 1, new [] { 4, 2, 3, } },
                { 2, new [] { 3 } },
                { 3, new [] { 1 } },
                { 4, new [] { 5 } },
                { 5, new [] { 4, 6 } },
                { 6, new [] { 4, } },
            };

            Scc <int> scc = new Scc <int>();

            scc.Find(g.Keys, v => g[v], (sccKey, sccVerticies, vs) => Console.WriteLine($"{sccKey}: {string.Join(", ", sccVerticies)}"));

            Dfs <int>         dfs        = new Dfs <int>();
            IEnumerable <int> traversed1 = dfs.Traverse2(g.Keys, v => g[v]);

            Console.WriteLine($"DFS 1: {string.Join(", ", traversed1)}");

            IEnumerable <int> traversed2 = dfs.Traverse2(g.Keys, v => g[v]);

            Console.WriteLine($"DFS 2: {string.Join(", ", traversed2)}");

            Console.Read();
        }
示例#7
0
文件: Model.cs 项目: haimgil1/ap2ex2
        /// <summary>
        /// Solves the maze DFS.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns>Solution</returns>
        public Solution <Position> solveMazeDFS(string name)
        {
            modelData.mutexDfs.WaitOne();
            Solution <Position> solution = null;

            // Check if the maze exist.
            if (modelData.Mazes.ContainsKey(name))
            {
                ISearchable <Position> mazeObjectAdapter = new MazeAdapter(modelData.Mazes[name]);
                ISearcher <Position>   DFS = new Dfs <Position>();
                // Check if the solution exist.
                if (modelData.DfsSolutions.ContainsKey(name))
                {
                    solution = modelData.DfsSolutions[name];
                }
                else
                {
                    // Calculate the solution.
                    solution = DFS.Search(mazeObjectAdapter);
                    modelData.DfsSolutions.Add(name, solution);
                }
            }

            State <Position> .StatePool.Clear();

            modelData.mutexDfs.ReleaseMutex();
            return(solution);
        }
示例#8
0
        /// <summary>
        /// add a solution to a maze.
        /// </summary>
        /// <param name="name">the name of the maze</param>
        /// <param name="searcher">the searcher algo</param>
        private void AddSolution(string name, int searcher)
        {
            // the solution.
            Solution <State <Position> > solution = new Solution <State <Position> >();
            int nodesEv = 0;
            ISearchable <Position> srMaze = new MazeSearchable(singleMazes[name]);

            // bfs algo.
            if (searcher == 0)
            {
                ISearcher <Position> bfs = new Bfs <Position>();
                solution = bfs.Search(srMaze);
                nodesEv  = bfs.GetNumberOfNodesEvaluated();
            }
            // dfs algo.
            else
            {
                ISearcher <Position> dfs = new Dfs <Position>();
                solution = dfs.Search(srMaze);
                nodesEv  = dfs.GetNumberOfNodesEvaluated();
            }
            string strSol = " ";

            // backtrace the maze solution.
            for (int i = solution.SolLst.Count - 1; i > 0; i--)
            {
                // went down.
                if (solution.SolLst[i].StateType.Row > solution.SolLst[i - 1].StateType.Row)
                {
                    strSol += "2";
                }
                // went up.
                else if (solution.SolLst[i].StateType.Row < solution.SolLst[i - 1].StateType.Row)
                {
                    strSol += "3";
                }
                // went left.
                else if (solution.SolLst[i].StateType.Col > solution.SolLst[i - 1].StateType.Col)
                {
                    strSol += "0";
                }
                // went right.
                else if (solution.SolLst[i].StateType.Col < solution.SolLst[i - 1].StateType.Col)
                {
                    strSol += "1";
                }
            }
            // the solution in json.
            JObject sol = new JObject
            {
                { "Name", name },
                { "Solution", strSol },
                { "NodesEvaluated", nodesEv }
            };
            string Jsol = JsonConvert.SerializeObject(sol);

            JsonConvert.DeserializeObject(Jsol);
            // add the solutin.
            solvedMazes.Add(name, Jsol);
        }
示例#9
0
        private void button_Click(object sender, RoutedEventArgs e)
        {
            var model = this.DataContext as ActionsVm;

            var parsedModel = ParseModel(model);

            Dfs dfs = new Dfs();
        }
示例#10
0
 private void Window_Loaded(object sender, RoutedEventArgs e)
 {
     _dfs = new Dfs();
     _dfs.Run();
     StartField = _dfs.StartField;
     CheckerGrid.DataContext = StartField;
     FinalField = _dfs.FinalField;
 }
示例#11
0
文件: DfsTest.cs 项目: Farga83/Algs4
 public void UndirectedPathToFiveHasTwoVertices()
 {
     var input = CreateTestInput();
     var g = new Graph(GraphType.Undirected, input, 7);
     var search = new Dfs(g, 0);
     var path = search.PathTo(5).ToArray();
     Assert.AreEqual(2, search.DistanceTo(5));
     Assert.AreEqual(2, path[0]);
     Assert.AreEqual(5, path[1]);
 }
示例#12
0
        public async Task DFS_should_add_and_read_text()
        {
            var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15));

            const string text = "good morning";
            var          dfs  = new Dfs(_ipfs, _hashProvider, _logger);
            var          id   = await dfs.AddTextAsync(text, cts.Token);

            var content = await dfs.ReadTextAsync(id, cts.Token);

            content.Should().Be(text);
        }
示例#13
0
 public void DFS(int v)
 {
     Dfs.Add(v);
     ChuaXet[v] = false;
     for (int i = 0; i < SoCot; i++)
     {
         if ((A[v, i] == 1) && (ChuaXet[i] == true))
         {
             DFS(i);
         }
     }
 }
示例#14
0
文件: DfsTest.cs 项目: Farga83/Algs4
 public void UndirectedConnectionsAreMarked()
 {
     var input = CreateTestInput();
     var g = new Graph(GraphType.Undirected, input, 7);
     var search = new Dfs(g, 0);
     Assert.IsTrue(search.Marked(2));
     Assert.IsTrue(search.Marked(3));
     Assert.IsTrue(search.Marked(5));
     Assert.IsFalse(search.Marked(1));
     Assert.IsFalse(search.Marked(4));
     Assert.IsFalse(search.Marked(6));
 }
示例#15
0
文件: DfsTest.cs 项目: Farga83/Algs4
 public void UndirectedHasPathToAreCorrect()
 {
     var input = CreateTestInput();
     var g = new Graph(GraphType.Undirected, input, 7);
     var search = new Dfs(g, 0);
     Assert.IsTrue(search.HasPathTo(2));
     Assert.IsTrue(search.HasPathTo(3));
     Assert.IsTrue(search.HasPathTo(5));
     Assert.IsFalse(search.HasPathTo(0)); // No path to self
     Assert.IsFalse(search.HasPathTo(1));
     Assert.IsFalse(search.HasPathTo(4));
     Assert.IsFalse(search.HasPathTo(6));
 }
示例#16
0
        public void TraverseActionCanGetAllVertices()
        {
            WeightedGraph <int> graph = new WeightedGraph <int>
            {
                (1, 2), (2, 3), (3, 4), (1, 4), (5, 2), (7, 2)
            };

            HashSet <int> vertices = new HashSet <int>();

            Dfs <int> dfs = new Dfs <int>(graph, edge => vertices.AddAll(new [] { edge.From, edge.To }));

            Assert.AreEqual(vertices.Count, graph.GetVertices().Count);
        }
示例#17
0
 /// <summary>
 /// solve maze
 /// </summary>
 /// <param name="name">name to solve</param>
 /// <param name="algoChoose">solve with...</param>
 /// <returns></returns>
 public Solution <Position> solveMaze(string name, int algoChoose)
 {
     // check if the solution is already exist..
     if (solutionCache.ContainsKey(name))
     {
         Solution <Position> sol = solutionCache[name];
         return(sol);
     }
     // check if we need caculste dfs or bfs
     if (algoChoose == 1)
     {
         // dfs
         if (poolMaze.ContainsKey(name))
         {
             Maze                maze           = poolMaze[name];
             MazeSearcher        mazeSearchable = new MazeSearcher(maze);
             Searcher <Position> dfsAlgo        = new Dfs <Position>();
             Solution <Position> sol1           = dfsAlgo.search(mazeSearchable);
             sol1.setEvaluatedNodes(dfsAlgo.getNumberOfNodesEvaluated());
             solutionCache.Add(name, sol1);
             return(sol1);
         }
         else
         {
             Console.WriteLine("Error in poolMaze request");
             return(null);
         }
     }
     else
     {
         // bfs
         if (poolMaze.ContainsKey(name))
         {
             Maze                maze           = poolMaze[name];
             MazeSearcher        mazeSearchable = new MazeSearcher(maze);
             Searcher <Position> bfsAlgo        = new Bfs <Position>();
             Solution <Position> sol2           = bfsAlgo.search(mazeSearchable);
             sol2.setEvaluatedNodes(bfsAlgo.getNumberOfNodesEvaluated());
             solutionCache.Add(name, sol2);
             return(sol2);
         }
         else
         {
             Console.WriteLine("Error in poolMaze request");
             return(null);
         }
     }
 }
示例#18
0
        /// <summary>
        /// Compares the solvers.
        /// </summary>
        public static void CompareSolvers()
        {
            DFSMazeGenerator generator = new DFSMazeGenerator();
            Maze             maze      = generator.Generate(10, 10);
            //Console.WriteLine(maze);
            ISearchable <Position> mazeAdapter = new MazeAdapter(maze);
            ISearcher <Position>   bfs         = new BestFirstSearch <Position>();
            ISearcher <Position>   dfs         = new Dfs <Position>();
            Solution <Position>    solution    = bfs.Search(mazeAdapter);

            Console.WriteLine("bfs sol:" + solution.EvaluatedNodes);
            Console.WriteLine(mazeAdapter.ToString(solution));
            solution = dfs.Search(mazeAdapter);
            Console.WriteLine("dfs sol:" + solution.EvaluatedNodes);
            Console.WriteLine(mazeAdapter.ToString(solution));
        }
        /// <summary>
        /// method that creates a maze and solves it by dfs and bfs
        /// </summary>
        public static void CompareSolvers()
        {
            DFSMazeGenerator maze        = new DFSMazeGenerator();
            Maze             currentMaze = maze.Generate(100, 100);

            Console.WriteLine(currentMaze.ToString());
            MazeSearcher         newMaze   = new MazeSearcher(currentMaze);
            ISearcher <Position> bfsSearch = new Bfs <Position>();
            ISearcher <Position> dfsSearch = new Dfs <Position>();
            Solution <Position>  solBfs    = bfsSearch.search(newMaze);
            Solution <Position>  solDfs    = dfsSearch.search(newMaze);

            //printing the num of evaluated nodes
            Console.WriteLine("bfs " + bfsSearch.EvaluatedNodes);
            Console.WriteLine("dfs " + dfsSearch.EvaluatedNodes);
            Console.ReadLine();
        }
示例#20
0
        public void CanSumUndirectedGraphWeightsCorrectlyWhenTraverseInDfsOrder()
        {
            WeightedGraph <int> graph = new WeightedGraph <int>
            {
                new WeightedEdge <int>(2, 3, 9),
                new WeightedEdge <int>(1, 2, 10),
                new WeightedEdge <int>(1, 3, 1),
                new WeightedEdge <int>(3, 4, 8),
                new WeightedEdge <int>(2, 5, 7),
                new WeightedEdge <int>(0, 5, 5)
            };
            double weight = 0;

            Dfs <int> dfs = new Dfs <int>(graph, edge => weight += edge.Weight);

            Assert.AreEqual(0, weight);
        }
示例#21
0
        public async Task DFS_should_add_and_read_binary()
        {
            var cts    = new CancellationTokenSource(TimeSpan.FromSeconds(15));
            var binary = new byte[]
            {
                1, 2, 3
            };
            var ms  = new MemoryStream(binary);
            var dfs = new Dfs(_ipfs, _hashProvider, _logger);
            var id  = await dfs.AddAsync(ms, "", cts.Token);

            using (var stream = await dfs.ReadAsync(id, cts.Token))
            {
                var content = new byte[binary.Length];
                stream.Read(content, 0, content.Length);
                content.Should().Equal(binary);
            }
        }
        public DfsTests()
        {
            _hashProvider = new HashProvider(HashingAlgorithm.GetAlgorithmMetadata("blake2b-256"));

            _ipfsEngine = Substitute.For <ICoreApi>();
            var fileSystem = Substitute.For <IFileSystemApi>();

            _ipfsEngine.FileSystem.Returns(fileSystem);

            var logger = Substitute.For <ILogger>();

            _expectedCid = CidHelper.CreateCid(_hashProvider.ComputeUtf8MultiHash("data"));

            _addedRecord = Substitute.For <IFileSystemNode>();
            _addedRecord.Id.ReturnsForAnyArgs(_expectedCid);
            _cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(DelayInMs));

            _dfs = new Dfs(_ipfsEngine, _hashProvider, logger);
        }
示例#23
0
        internal void EnumerateVertices(GraphParameter <Graph> p)
        {
            SimpleIncidenceGraph graph = p.Graph;

            // Arrange

            int source = graph.VertexCount >> 1;

            byte[] setBackingStore = ArrayPool <byte> .Shared.Rent(Math.Max(graph.VertexCount, source + 1));

            Array.Clear(setBackingStore, 0, setBackingStore.Length);
            IndexedSet exploredSet = new(setBackingStore);

            // Act

            IEnumerator <int> basicSteps      = Dfs.EnumerateVertices(graph, source, graph.VertexCount) !;
            IEnumerator <int> enumerableSteps = EnumerableDfs.EnumerateVertices(graph, source, exploredSet) !;

            // Assert

            while (true)
            {
                bool expectedHasCurrent = enumerableSteps.MoveNext();
                bool actualHasCurrent   = basicSteps.MoveNext();

                Assert.Equal(expectedHasCurrent, actualHasCurrent);

                if (!expectedHasCurrent || !actualHasCurrent)
                {
                    break;
                }

                int expected = enumerableSteps.Current;
                int actual   = basicSteps.Current;

                if (expected != actual)
                {
                    Assert.Equal(expected, actual);
                    break;
                }
            }
        }
示例#24
0
        public JObject GetSolve(string name, int alg)
        {
            ISearcher <Position> algorithm;

            if (alg == 0)
            {
                //BFS way
                algorithm = new Bfs <Position>();
            }
            else
            {
                //DFS way
                algorithm = new Dfs <Position>();
            }
            String  mazeSolve = myModel.solve(name, algorithm);
            JObject solveObj  = new JObject();

            solveObj["Solution"] = mazeSolve;
            return(solveObj);
        }
示例#25
0
        /// <summary>
        /// compare the slovers.
        /// </summary>
        public void compareSolvers()
        {
            DFSMazeGenerator mazeCreator    = new DFSMazeGenerator();
            Maze             maze           = mazeCreator.Generate(25, 25);
            MazeSearcher     mazeSearchable = new MazeSearcher(maze);
            // dfs
            Searcher <Position> dfsAlgo = new Dfs <Position>();
            Solution <Position> sol1    = dfsAlgo.search(mazeSearchable);

            Console.WriteLine(dfsAlgo.getNumberOfNodesEvaluated());
            List <State <Position> > pathdfs = sol1.getList();
            // bfs
            Searcher <Position> bfsAlgo = new Bfs <Position>();
            // MazeSearcher mazeSearchable = new MazeSearcher(maze);
            Solution <Position> sol2 = bfsAlgo.search(mazeSearchable);

            Console.WriteLine(bfsAlgo.getNumberOfNodesEvaluated());
            List <State <Position> > pathbfs = sol2.getList();

            foreach (State <Position> s in pathdfs)
            {
                int x = s.getState().Row;
                int y = s.getState().Col;

                Console.Write("({0},{1}), ", x, y);
            }
            Console.WriteLine();
            // convert maze to string before the print
            String mazeString = maze.ToString();

            Console.WriteLine(mazeString);
            Console.WriteLine();
            foreach (State <Position> s in pathbfs)
            {
                int x = s.getState().Row;
                int y = s.getState().Col;
                Console.Write("({0},{1}) ", x, y);
            }
            Console.ReadKey();
        }
示例#26
0
        /// <summary>
        /// Executes the commands that the client sent
        /// </summary>
        /// <param name="args">The arguments of the commands.</param>
        /// <param name="client">The client that sent the command.</param>
        /// <returns>a string of the result to the client</returns>
        public string Execute(string[] args, TcpClient client)
        {
            string name          = args[0];
            int    algorithmType = int.Parse(args[1]);
            ISearcher <Position> algorithm;

            //find what algorithm it is
            if (algorithmType == 0)
            {
                //BFS way
                algorithm = new Bfs <Position>();
            }
            else
            {
                //DFS way
                algorithm = new Dfs <Position>();
            }
            string sol            = model.solve(name, algorithm);
            int    nodesEvaluated = algorithm.EvaluatedNodes;

            return(ToJSON(name, sol, nodesEvaluated));
        }
示例#27
0
        public void Test_Dfs_Matrix_Directed()
        {
            Graph g = new GraphM(7);

            g.SetEdge(0, 1, 2);
            g.SetEdge(0, 2, 1);
            g.SetEdge(0, 3, 1);
            g.SetEdge(0, 4, 1);
            g.SetEdge(1, 5, 1);
            g.SetEdge(2, 5, 1);
            g.SetEdge(3, 6, 1);
            g.SetEdge(5, 4, 1);
            g.SetEdge(6, 4, 1);
            g.SetEdge(6, 5, 1);


            ITravel dfs = new Dfs(g, preVisit);

            dfs.Travel(0);
            Assert.AreEqual(10, g.EdgeNum());
            Assert.AreEqual("0154236", stringBuilder.ToString());
        }
示例#28
0
        /// <summary>
        /// compares between a bfs and dfs searchers on a maze.
        /// </summary>
        public static void CompareSolvers()
        {
            IMazeGenerator gen = new DFSMazeGenerator();
            // get a random maze size 50X50.
            Maze maze = gen.Generate(50, 50);

            /// print the maze.
            Console.Write(maze);
            // make the maze searchable.
            ISearchable <Position> myMaze = new MazeSearchable(maze);
            // bfs solution.
            ISearcher <Position> bfs = new Bfs <Position>();

            bfs.Search(myMaze);
            // dfs solution.
            ISearcher <Position> dfs = new Dfs <Position>();

            dfs.Search(myMaze);
            // write number of nodes evaluated in each search.
            Console.WriteLine(bfs.GetNumberOfNodesEvaluated());
            Console.WriteLine(dfs.GetNumberOfNodesEvaluated());
            Console.ReadKey();
        }
示例#29
0
        public static void Client()
        {
            var vertices = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            var edges    = new[]
            {
                Tuple.Create(1, 2), Tuple.Create(1, 3), Tuple.Create(2, 4),
                Tuple.Create(3, 5), Tuple.Create(3, 6), Tuple.Create(4, 7),
                Tuple.Create(5, 7), Tuple.Create(5, 8), Tuple.Create(5, 6),
                Tuple.Create(8, 9), Tuple.Create(9, 10), Tuple.Create(8, 10),
            };

            var graph = new Graph <int>(vertices, edges);
            var dfs   = new Dfs();

            var path = new List <int>();

            // Tracing DFS path
            Console.WriteLine(string.Join(", ", dfs.ApplyDfs(graph, 1, v => path.Add(v))));
            // 1, 3, 6, 5, 8, 10, 9, 7, 4, 2

            Console.WriteLine(string.Join(", ", path));
            // 1, 3, 6, 5, 8, 10, 9, 7, 4, 2
        }
示例#30
0
文件: Program.cs 项目: mordehg/ex2
        /// <summary>
        /// Roy's example.
        /// </summary>
        public static void test()
        {
            string json = @"{
                'Name': 'mymaze',
                'Maze':
                '0001010001010101110101010000010111111101000001000111010101110001010001011111110100000000011111111111',
                'Rows': 10,
                'Cols': 10,
                'Start': {
                    'Row': 0,
                    'Col': 4
                },
                'End': {
                    'Row': 0,
                    'Col': 0
                }
            }";
            Maze   maze = Maze.FromJSON(json);

            Console.Write(maze.ToString());
            Adapter <Position>     adapter        = new MazeToSearchableAdapter <Position>(maze);
            ISearchable <Position> searchableMaze = new Searchable <Position, Direction>(adapter);
            ISearcher <Position>   bfs            = new Bfs <Position>();
            ISearcher <Position>   dfs            = new Dfs <Position>();
            Solution <Position>    solBfs         = bfs.Search(searchableMaze);
            Solution <Position>    solDfs         = dfs.Search(searchableMaze);

            Console.WriteLine("bfs " + solBfs.NodesEvaluated.ToString());
            SolutionRepresent <MazeLib.Direction, MazeLib.Position, int> solRepresent = new MazeSolRepreset(solBfs);

            solRepresent.ConvertSolution();

            Console.WriteLine("bfs sol " + solRepresent.ToJSON());
            Console.WriteLine("dfs " + solDfs.NodesEvaluated);
            Console.ReadKey();
        }
示例#31
0
        private bool AddNewScenarioResultAndLogFiles(string FileName, MikeScenario CurrentMikeScenario)
        {
            richTextBoxStatus.AppendText("\r\n\r\nFile [" + FileName + "]\r\n");

            FileInfo   fi = new FileInfo(FileName);
            FileStream fs = fi.OpenRead();

            string FilePath      = FileName.Substring(0, FileName.LastIndexOf("\\") + 1);
            string ShortFileName = FileName.Substring(FileName.LastIndexOf("\\") + 1);

            Application.DoEvents();

            //Read all file bytes into an array from the specified file.
            int nBytes = (int)fi.Length;

            Byte[] ByteArray  = new byte[nBytes];
            int    nBytesRead = fs.Read(ByteArray, 0, nBytes);

            fs.Close();

            richTextBoxStatus.AppendText("Checking if file already in DB ...\r\n");
            Application.DoEvents();

            //string TheFileName = fi.FullName.Substring(fi.FullName.LastIndexOf("\\") + 1);
            CSSPFile csspFileExist = (from f in vpse.CSSPFiles
                                      where f.FileName == ShortFileName &&
                                      f.FileOriginalPath == FilePath &&
                                      f.FileType == fi.Extension
                                      select f).FirstOrDefault <CSSPFile>();

            if (csspFileExist != null)
            {
                // just replace the content of the file
                richTextBoxStatus.AppendText("File already exist in DB ...\r\n");
                richTextBoxStatus.AppendText("Updating the fileContent in DB ...\r\n");
                csspFileExist.FileContent = ByteArray;

                try
                {
                    vpse.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
                    richTextBoxStatus.AppendText("fileContent updated ...\r\n");
                    return(true);
                }
                catch (Exception ex)
                {
                    richTextBoxStatus.AppendText("Error while updating fileContent ...\r\n");
                    richTextBoxStatus.AppendText("Error message [" + ex.Message + "] ...\r\n");
                    lblStatusWorking.Text = "Error ... ";
                    lblStatusUpdate.Text  = "See details below ... ";
                    return(false);
                }
            }

            richTextBoxStatus.AppendText("File does not exist in DB ...\r\n");
            richTextBoxStatus.AppendText("Saving file in DB ...\r\n");
            Application.DoEvents();

            CSSPFile csspFile = new CSSPFile();

            csspFile.CSSPGuid         = Guid.NewGuid();
            csspFile.FileName         = ShortFileName;
            csspFile.FileOriginalPath = FilePath;
            csspFile.FileSize         = fi.Length;
            csspFile.FileDescription  = "";
            csspFile.FileCreatedDate  = fi.CreationTime;
            csspFile.FileType         = fi.Extension;
            csspFile.FileContent      = ByteArray;
            if (fi.Extension.ToLower() == ".dfsu")
            {
                csspFile.Purpose = PurposeType.MikeResult.ToString();

                MemoryStream ms = new MemoryStream(ByteArray);

                Dfs dfs = new Dfs(Dfs.DFSType.DFSU, true);

                dfs.StreamToDfs(ms);

                csspFile.DataStartDate     = dfs.DataStartDate;
                csspFile.DataEndDate       = dfs.DataStartDate.AddSeconds(dfs.TimeSteps * dfs.XValueList.Count);
                csspFile.TimeStepsInSecond = dfs.TimeSteps;
                string ParamNameTxt = "";
                string ParamUnitTxt = "";
                foreach (Dfs.Parameter p in dfs.ParameterList)
                {
                    ParamUnitTxt += string.Format("[{0}]-", p.UnitCode.ToString());
                    ParamNameTxt += string.Format("[{0}]-", p.Description);
                }
                csspFile.ParameterNames = ParamNameTxt.Substring(0, ParamNameTxt.Length - 1);
                csspFile.ParameterUnits = ParamUnitTxt.Substring(0, ParamUnitTxt.Length - 1);
            }
            else if (fi.Extension.ToLower() == ".log")
            {
                csspFile.Purpose = PurposeType.MikeResult.ToString();
            }
            else
            {
                richTextBoxStatus.AppendText("File extension should only be .dfsu and .log. It is [" + fi.Extension + "] ...\r\n");
                return(false);
            }

            try
            {
                vpse.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
                richTextBoxStatus.AppendText("CSSPFile saved in DB ...\r\n");
                Application.DoEvents();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not store file [" + FileName + "] in DB\r\n" + ex.Message + "\r\n");
                richTextBoxStatus.AppendText("Could not store file [" + FileName + "] in DB\r\n" + ex.Message + "\r\n");
                Application.DoEvents();
                lblStatusWorking.Text = "Error ... ";
                lblStatusUpdate.Text  = "See details below ... ";
                return(false);
            }

            int msID = CurrentMikeScenario.MikeScenarioID;

            CurrentMikeScenario = (from ms in vpse.MikeScenarios
                                   where ms.MikeScenarioID == msID
                                   select ms).FirstOrDefault <MikeScenario>();

            if (CurrentMikeScenario == null)
            {
                richTextBoxStatus.AppendText("Could not find MikeScenario with MikeScenarioID = [" + msID + "] ...\r\n");
                lblStatusWorking.Text = "Error ... ";
                lblStatusUpdate.Text  = "See details below ... ";
                return(false);
            }

            MikeScenarioFile NewMikeScenarioFile = new MikeScenarioFile();

            NewMikeScenarioFile.MikeScenario   = CurrentMikeScenario;
            NewMikeScenarioFile.CSSPFile       = csspFile;
            NewMikeScenarioFile.CSSPParentFile = csspFile;

            try
            {
                richTextBoxStatus.AppendText("Linking MikeScenario to CSSPFile using MikeScenarioFile ...\r\n");
                Application.DoEvents();
                vpse.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
                richTextBoxStatus.AppendText("Linked MikeScenario to CSSPFile using MikeScenarioFile ...\r\n");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not link MikeScenario to CSSPFile\r\n" + ex.Message + "\r\n");
                richTextBoxStatus.AppendText("Could not link MikeScenario to CSSPFile\r\n" + ex.Message + "\r\n");
                Application.DoEvents();
                lblStatusWorking.Text = "Error ... ";
                lblStatusUpdate.Text  = "See details below ... ";
                return(false);
            }

            return(true);
        }
示例#32
0
    protected void import_SystemTableData(CRecord tblRec)
    {
        CDatafields Dfs;
        CDatafield  Df = new CDatafield();

        switch (tblRec.Controlfields.Controlfield("001").Value)
        {
        case "LEGOWEB_COMMON_PARAMETERS":
            //Df.SubfieldsText = String.Format("$a{0} $b{1} $c{2} $d{3} $e{4}", row["PARAMETER_NAME"].ToString(), row["PARAMETER_TYPE"].ToString(), row["PARAMETER_VI_VALUE"].ToString(), row["PARAMETER_EN_VALUE"].ToString(), row["PARAMETER_DESCRIPTION"].ToString());
            Dfs = tblRec.Datafields;
            Dfs.Filter("650");
            for (int i = 0; i < Dfs.Count; i++)
            {
                Df = Dfs.Datafield(i);
                LegoWebAdmin.BusLogic.CommonParameters.addudp_LEGOWEB_COMMON_PARAMETER(Df.Subfields.Subfield("a").Value, int.Parse(Df.Subfields.Subfield("b").Value), Df.Subfields.Subfield("c").Value, Df.Subfields.Subfield("d").Value, Df.Subfields.Subfield("e").Value);
            }
            break;

        case "LEGOWEB_SECTIONS":
            //Df.SubfieldsText = String.Format("$a{0} $b{1} $c{2}", row["SECTION_ID"].ToString(), row["SECTION_VI_TITLE"].ToString(), row["SECTION_EN_TITLE"].ToString());
            Dfs = tblRec.Datafields;
            Dfs.Filter("650");
            for (int i = 0; i < Dfs.Count; i++)
            {
                Df = Dfs.Datafield(i);
                LegoWebAdmin.BusLogic.Sections.add_Update(int.Parse(Df.Subfields.Subfield("a").Value), Df.Subfields.Subfield("b").Value, Df.Subfields.Subfield("c").Value);
            }
            break;

        case "LEGOWEB_CATEGORIES":
            //Df.SubfieldsText = String.Format("$a{0} $b{1} $c{2} $d{3} $e{4} $f{5} $g{6} $h{7} $i{8} $j{9} $k{10} $l{11} $m{12} $n{13} $o{14} $p{15}", row["CATEGORY_ID"].ToString(), row["PARENT_CATEGORY_ID"].ToString(), row["SECTION_ID"].ToString(), row["CATEGORY_VI_TITLE"].ToString(), row["CATEGORY_EN_TITLE"].ToString(), row["CATEGORY_ALIAS"].ToString(), row["CATEGORY_TEMPLATE_NAME"].ToString(), row["CATEGORY_IMAGE_URL"].ToString(), row["MENU_ID"].ToString(), row["IS_PUBLIC"].ToString(), row["ADMIN_LEVEL"].ToString(), row["ADMIN_ROLES"].ToString(), row["SEO_TITLE"].ToString(), row["SEO_DESCRIPTION"].ToString(), row["SEO_KEYWORDS"].ToString(),row["ORDER_NUMBER"].ToString());

            Dfs = tblRec.Datafields;
            Dfs.Filter("650");
            for (int i = 0; i < Dfs.Count; i++)
            {
                Df = Dfs.Datafield(i);
                LegoWebAdmin.BusLogic.Categories.addUpdate_CATEGORY(int.Parse(Df.Subfields.Subfield("a").Value), int.Parse(Df.Subfields.Subfield("b").Value), int.Parse(Df.Subfields.Subfield("c").Value), Df.Subfields.Subfield("d").Value, Df.Subfields.Subfield("e").Value, Df.Subfields.Subfield("f").Value, Df.Subfields.Subfield("g").Value, Df.Subfields.Subfield("h").Value, int.Parse(Df.Subfields.Subfield("i").Value), int.Parse("0" + Df.Subfields.Subfield("q").Value), Convert.ToBoolean(Df.Subfields.Subfield("j").Value), int.Parse(Df.Subfields.Subfield("k").Value), Df.Subfields.Subfield("l").Value, Df.Subfields.Subfield("m").Value, Df.Subfields.Subfield("n").Value, Df.Subfields.Subfield("o").Value);
                if (!String.IsNullOrEmpty(Df.Subfields.Subfield("p").Value))
                {
                    LegoWebAdmin.BusLogic.Categories.update_CATEGORY_ORDER(int.Parse(Df.Subfields.Subfield("a").Value), int.Parse(Df.Subfields.Subfield("p").Value));
                }
            }
            break;

        case "LEGOWEB_MENU_TYPES":
            //Df.SubfieldsText = String.Format("$a{0} $b{1} $c{2} $d{3}", row["MENU_TYPE_ID"].ToString(), row["MENU_TYPE_VI_TITLE"].ToString(), row["MENU_TYPE_EN_TITLE"].ToString(), row["MENU_TYPE_DESCRIPTION"].ToString());
            Dfs = tblRec.Datafields;
            Dfs.Filter("650");
            for (int i = 0; i < Dfs.Count; i++)
            {
                Df = Dfs.Datafield(i);
                LegoWebAdmin.BusLogic.MenuTypes.addUpdate_MenuType(int.Parse(Df.Subfields.Subfield("a").Value), Df.Subfields.Subfield("b").Value, Df.Subfields.Subfield("c").Value, Df.Subfields.Subfield("d").Value);
            }
            break;


        case "LEGOWEB_MENUS":
            //Df.SubfieldsText = String.Format("$a{0} $b{1} $c{2} $d{3} $e{4} $f{5} $g{6} $h{7} $i{8} $j{9}", row["MENU_ID"].ToString(), row["PARENT_MENU_ID"].ToString(), row["MENU_TYPE_ID"].ToString(), row["MENU_VI_TITLE"].ToString(), row["MENU_EN_TITLE"].ToString(), row["MENU_IMAGE_URL"].ToString(), row["MENU_LINK_URL"].ToString(), row["BROWSER_NAVIGATE"].ToString(), row["IS_PUBLIC"].ToString(),row["ORDER_NUMBER"].ToString());
            Dfs = tblRec.Datafields;
            Dfs.Filter("650");
            for (int i = 0; i < Dfs.Count; i++)
            {
                Df = Dfs.Datafield(i);
                LegoWebAdmin.BusLogic.Menus.addUpdate_MENU(int.Parse(Df.Subfields.Subfield("a").Value), int.Parse(Df.Subfields.Subfield("b").Value), int.Parse(Df.Subfields.Subfield("c").Value), Df.Subfields.Subfield("d").Value, Df.Subfields.Subfield("e").Value, Df.Subfields.Subfield("f").Value, Df.Subfields.Subfield("g").Value, int.Parse(Df.Subfields.Subfield("h").Value), Convert.ToBoolean(Df.Subfields.Subfield("i").Value));
                if (!String.IsNullOrEmpty(Df.Subfields.Subfield("j").Value))
                {
                    LegoWebAdmin.BusLogic.Menus.update_MENU_ORDER(int.Parse(Df.Subfields.Subfield("a").Value), int.Parse(Df.Subfields.Subfield("j").Value));
                }
            }
            break;
        }
    }
示例#33
0
 public ValuesController(Dfs dfs)
 {
     obj = dfs;
 }