/// <summary> /// 是否包含匹配结果 /// </summary> /// <param name="text"></param> /// <returns></returns> public bool ContainsKey(string text) { SearchTree st = _Root; int index = 0; while (index < text.Length) { SearchTree node = null; while (node == null) { node = st.GetTransition(text[index]); if (node == null) { st = st.Failure; } if (st == node) { break; } } if (node != null) { st = node; } if (st.Results.Length > 0) { return(true); } index++; } return(false); }
protected override IEnumerable <string> PerformSearch(string path) { foreach (var file in SearchTree.GetLeaves(path, Expression)) { yield return(file); } }
public static T DepthFirstSearchRecursive <T>( this SearchTree <T> tree, Func <T, bool> matchFunc) where T : class { return(tree.Root.DepthFirstSearchRecursive(matchFunc)); }
public ActionResult DeepSearchTreeAlgorithm(string data, int start) { var matrix = JsonConvert.DeserializeObject <int[, ]>(data); Object result; try { if (matrix == null) { return(null); } var method = new SearchTree(); var resultMatrix = method.StartDeepSearch(matrix, start); result = new { exception = "", matrix = resultMatrix }; } catch (MethodException ex) { result = new { exception = ex.Message }; } return(Json(result, JsonRequestBehavior.AllowGet)); }
public bool SearchTree_IEnumerableConstructor(int[] array, int elem) { var list = new List <int>(array); var tree = new SearchTree <int>(list); return(tree.Contains(elem)); }
public void InsertNode(T newItem) { T currentNodeValue = this.NodeData; if (currentNodeValue.CompareTo(newItem) > 0) { if (this.LeftTree == null) { this.LeftTree = new SearchTree <T>(newItem); } else { this.LeftTree.InsertNode(newItem); } } else { if (this.RightTree == null) { this.RightTree = new SearchTree <T>(newItem); } else { this.RightTree.InsertNode(newItem); } } }
/// <summary> /// 查找首个匹配结果 /// </summary> /// <param name="text"></param> /// <returns></returns> public FastReplaceResult FindFirst(string text) { SearchTree st = _Root; int index = 0; while (index < text.Length) { SearchTree node = null; while (node == null) { node = st.GetTransition(text[index]); if (node == null) { st = st.Failure; } if (st == node) { break; } } if (node != null) { st = node; } foreach (ReplaceKeyValue found in st.Results) { return(new FastReplaceResult(index - found.Key.Length + 1, found)); } index++; } return(FastReplaceResult.Empty); }
/// <summary> /// /// </summary> /// <param name="filter"></param> /// <param name="tree"></param> private void SearchFolders(DashboardSearchFilter filter, SearchTree tree, ModelTeams teams) { var shouldReturn = (null != filter.FolderIds && !filter.FolderIds.Contains(0)) || (filter.Starred) || (filter.HasTags) || (filter.HasDashboardIds); if (shouldReturn) { return; } var request = DataContext .Folders .ForActiveOrg() .Include(x => x.Permissions) .AsQueryable(); if (!string.IsNullOrEmpty(filter.Query)) { request = request .Where(x => x.Title.ToLower().Contains(filter.Query.ToLower())); } var folders = request.ToList(); tree.Folders = folders .Where(x => CheckViewPermission(x, teams)) .Select(x => x.ToModel()) .ToList(); }
/// <summary> /// 新增节点 /// </summary> /// <param name="node"></param> public void AddTransition(SearchTree node) { _TransHash.Add(node.Char, node); SearchTree[] st = new SearchTree[_TransHash.Values.Count]; _TransHash.Values.CopyTo(st, 0); _Transitions = st; }
/// <summary> /// /// </summary> /// <param name="filter"></param> /// <returns></returns> public OperationResult <SearchTree> Search(DashboardSearchFilter filter) { //return OperationResult<SearchTree>.Create( ErrorCode.BadGetDashboards); var tree = new SearchTree(); OperationResult <SearchTree> res = null; try { var teams = new UserRepository(DataContext) .ForActiveOrg(DataContext.ActiveOrgId) .GetUserTeams(DataContext.ActiveUserId) .Value ?? new ModelTeams(); SearchDashboards(filter, tree, teams); SearchFolders(filter, tree, teams); res = OperationResult <SearchTree> .Create(tree); } catch //( Exception ) { //res = OperationResult<ModelDashboards>.Create( ErrorCode.BadGetDashboards, e ); } return(res); }
private void IDNaiveButton_Click(object sender, EventArgs e) { var tree = new SearchTree <Problems.SlidingTilesPuzzle.State>(_currentState); var dfs = new DepthFirstSearcher <Problems.SlidingTilesPuzzle.State, int>( tree, x => x.GetActions(), (x, a) => x.Clone().ApplyAction(a), (x, a) => 1, x => x.IsSolution); var id = new IterativeDeepeningDepthFirstSearch <Problems.SlidingTilesPuzzle.State, int>(dfs); var updateCount = 0; var start = DateTime.Now; Action <bool> updateCounts = (force) => { if (!force && ++updateCount % 10000 > 0) { return; } NodesGeneratedLabel.Text = "Generated = " + dfs.NodesGeneratedCount + " "; ExpandedNodesLabel.Text = "Expanded = " + dfs.NodesExpandedCount + " "; RetainedNodesLabel.Text = "Retained = " + dfs.NodesRetainedCount + " "; SecondsLabel.Text = DateTime.Now.Subtract(start).TotalSeconds.ToString() + " (next depth = " + dfs.NextCostThreshhold + ")"; _currentState = dfs.CurrentNode.Data; panel1.Invalidate(); Application.DoEvents(); }; dfs.NodeExpanded += (s, a) => updateCounts(false); dfs.NodeGenerated += (s, a) => updateCounts(false); var solution = id.Search(); updateCounts(true); }
public bool SearchTree_CustomPoint_CustomComparer(int first, int second) { int compare(Point a, Point b) { if (a.X > b.X) { return(1); } if (a.X < b.X) { return(-1); } return(0); } var array = new Point[] { new Point(10, 15), new Point(15, 55), new Point(20, 45) }; var tree = new SearchTree <Point>(compare); for (int i = 0; i < array.Length; i++) { tree.Add(array[i]); } return(tree.Contains(new Point(first, second))); }
public bool SearchTree_CustomBook_CustomComparer(int elem) { int compare(Book a, Book b) { if (a.Price > b.Price) { return(1); } if (a.Price < b.Price) { return(-1); } return(0); } var array = new Book[] { new Book(10), new Book(15), new Book(20) }; var tree = new SearchTree <Book>(compare); for (int i = 0; i < array.Length; i++) { tree.Add(array[i]); } return(tree.Contains(new Book(elem))); }
public bool SearchTree_ContainsMethodString_CustomComparer(string elem) { int compare(string a, string b) { if (a.CompareTo(b) > 0) { return(1); } if (a.CompareTo(b) < 0) { return(-1); } return(0); } var array = new string[] { "dog", "city", "hello" }; var tree = new SearchTree <string>(compare); for (int i = 0; i < array.Length; i++) { tree.Add(array[i]); } return(tree.Contains(elem)); }
internal static SearchTree GenerateSearchTreeCommon(Dictionary <int, Executable[]> codeByLookup, int min, int max) { if (min == max) { return(new SearchTree() { Code = codeByLookup[min] }); } if (min + 1 == max) { SearchTree left = new SearchTree() { Code = codeByLookup[min] }; SearchTree right = new SearchTree() { Code = codeByLookup[max] }; return(new SearchTree() { LessThanThis = max, Left = left, Right = right }); } int mid = (min + max + 1) / 2; return(new SearchTree() { LessThanThis = mid, Left = GenerateSearchTreeCommon(codeByLookup, min, mid - 1), Right = GenerateSearchTreeCommon(codeByLookup, mid, max) }); }
/// <summary> /// 查找所有匹配结果 /// </summary> /// <param name="text"></param> /// <returns></returns> public List <FastReplaceResult> FindAll(string text) { List <FastReplaceResult> results = new List <FastReplaceResult>(); SearchTree st = _Root; int index = 0; while (index < text.Length) { SearchTree node = null; while (node == null) { node = st.GetTransition(text[index]); if (st == _Root) { break; } if (node == null) { st = st.Failure; } } if (node != null) { st = node; } foreach (ReplaceKeyValue found in st.Results) { results.Add(new FastReplaceResult(index - found.Key.Length + 1, found)); } index++; } return(results); }
public void GetMove_Initial_Performance() { var tree = new SearchTree(); var act = tree.GetMove(Field.Empty, TimeSpan.MaxValue, TimeSpan.FromSeconds(5)); Console.WriteLine(tree.Logger); var exp = (byte)3; Assert.AreEqual(exp, act); }
/// <summary> /// /// </summary> /// <param name="filter"></param> /// <param name="tree"></param> private void SearchDashboards(DashboardSearchFilter filter, SearchTree tree, ModelTeams teams) { var request = DataContext .Dashboards .ForActiveOrg() .AsQueryable(); if (filter.HasFolderIds) { request = request.Where(d => (null == d.FolderId && filter.FolderIds.Contains(0)) ? true : (null != d.FolderId && filter.FolderIds.Contains(d.FolderId.Value))); } if (!string.IsNullOrEmpty(filter.Query)) { request = request .Where(x => x.Title.ToLower().Contains(filter.Query.ToLower())); } if (filter.Starred) { request = request .Where(x => x.Stars.Any(y => y.UserId == filter.UserId)); } if (filter.HasDashboardIds) { request = request .Where(x => filter.DashboardIds.Contains(x.Id)); } var dashboards = request .Include(x => x.Folder) .ThenInclude(x => x.Permissions) .Include(x => x.Tags) .Include(x => x.Stars) .Include(x => x.Permissions) .ToList() .Where(x => CheckViewPermission(x, teams)) .Select(x => x .ToModel() .AddVersion(DataContext.Entry(x))) .ToList(); if (filter.HasTags) { Func <ModelDashboard, bool> tagPred = x => (filter.TagOperator == SearchOperator.And) ? filter.Tags.Intersect(x.Tags).Count() == filter.Tags.Count() : x.Tags.Intersect(filter.Tags).Count() > 0; dashboards = dashboards .Where(tagPred) .ToList(); } tree.Dashboards = dashboards; }
public MoveInfo(IBlock curBlock, SearchTree tree, int curIndex, ScriptFile sf) { CurrentBlock = curBlock; CurrentIndex = curIndex; TreeMode = tree; this.errorInfo = new ErrorInfo(sf); CurrentElements = GetBlockElems(curBlock); treeInfoStack = new Stack <TreeInfo>(); }
/// <summary> /// 构建搜索树<see cref="SearchTree"/>的新实例 /// </summary> /// <param name="_Parent">母节点</param> /// <param name="_Char">字</param> public SearchTree(SearchTree _Parent, char _Char) { this._Char = _Char; this._Parent = _Parent; _Results = new ArrayList(); _ResultsArray = new ReplaceKeyValue[] { }; _Transitions = new SearchTree[] { }; _TransHash = new Hashtable(); }
public void SearchTree_MalformedSources_NoMatch(string packagePatterns, string term) { // Arrange SearchTree searchTree = GetSearchTree(packagePatterns); // Act & Assert IReadOnlyList <string> configuredSources = searchTree.GetConfiguredPackageSources(term); Assert.Null(configuredSources); }
public void Setup() { firstKey = 2; firstData = 2; secondKey = 1; secondData = 4; searchTree = new SearchTree(); searchTree.Insert(firstKey, firstData); searchTree.Insert(secondKey, secondData); }
public void SearchTree_WithMultipleSources_NoMatch(string packageNamespaces, string term) { // Arrange SearchTree searchTree = GetSearchTree(packageNamespaces); // Act & Assert IReadOnlyList <string> configuredSources = searchTree.GetConfiguredPackageSources(term); Assert.Null(configuredSources); }
public void SearchTree_TopNodeIsGlobbing_NoMatch(string packageNamespaces, string term) { // Arrange SearchTree searchTree = GetSearchTree(packageNamespaces); // Act & Assert var packageSourcesMatch = searchTree.GetConfiguredPackageSources(term); Assert.Null(packageSourcesMatch); }
private SearchTree <TestPayload> CreateTestTree(params int[] start) { var tree = new SearchTree <TestPayload>(); for (int i = 0; i < start.Length; i++) { tree.Add(new TestPayload(start[i], i + 1)); } return(tree); }
public Agent(LogarithmicGrid startingGrid, ISearcherFactory searcherFactory, IHeuristic heuristic) { this.searcherFactory = searcherFactory; this.searchTree = new SearchTree(heuristic, startingGrid); this.Timings.Add(1, Duration.Zero); if (startingGrid.Flatten().Any(i => i == 2)) { this.Timings.Add(2, Duration.Zero); } }
public bool SearchTree_ContainsMethod(int[] array, int elem) { var tree = new SearchTree <int>(); for (int i = 0; i < array.Length; i++) { tree.Add(array[i]); } return(tree.Contains(elem)); }
public int SearchTree_ContProperty(int[] array) { var tree = new SearchTree <int>(); for (int i = 0; i < array.Length; i++) { tree.Add(array[i]); } return(tree.Count); }
public void SearchTree_WithMultipleSources_Match(string packageNamespaces, string term) { // Arrange PackageNamespacesConfiguration configuration = PackageNamespacesConfigurationUtility.GetPackageNamespacesConfiguration(packageNamespaces); SearchTree searchTree = new SearchTree(configuration); // Act & Assert IReadOnlyList <string> configuredSources = searchTree.GetConfiguredPackageSources(term); Assert.Equal(1, configuredSources.Count); Assert.True(configuredSources[0].StartsWith(term.Trim().Substring(0, 5))); }
public SearchTree <Person> IdealToSearchTree() { foreach (Person item in this) { list.Add(item); } Person[] arr = list.ToArray(); SearchTree <Person> tree = new SearchTree <Person>(arr); list.Clear(); return(tree); }
public void SearchTree_InternationalSources_MatchesWithOne(string packagePatterns, string term) { // Arrange var configuration = PackageSourceMappingUtility.GetpackageSourceMapping(packagePatterns); SearchTree searchTree = new SearchTree(configuration); // Act & Assert IReadOnlyList <string> configuredSources = searchTree.GetConfiguredPackageSources(term); Assert.Equal(1, configuredSources.Count); Assert.True(term.Trim().StartsWith(configuredSources[0], StringComparison.OrdinalIgnoreCase)); }
public void GetMove_ResponseOnCol0_Performance() { var field = Field.Parse(@" 0,0,0,0,0,0,0; 0,0,0,0,0,0,0; 0,0,0,0,0,0,0; 0,0,0,0,0,0,0; 0,0,0,0,0,0,0; 0,0,0,0,0,0,1"); var tree = new SearchTree(); var act = tree.GetMove(field, TimeSpan.MaxValue, TimeSpan.FromSeconds(2)); Console.WriteLine(tree.Logger); Assert.AreEqual(Scores.YelWin, tree.Root.Score); }
public void GetMove_ResponseOnCol3_Performance() { var field = Field.Parse(@" 0,0,0,0,0,0,0; 0,0,0,0,0,0,0; 0,0,0,0,0,0,0; 0,0,0,0,0,0,0; 0,0,0,0,0,0,0; 0,0,0,1,0,0,0"); var tree = new SearchTree(); var time = TimeSpan.FromSeconds(2); var act = tree.GetMove(field, TimeSpan.MaxValue, time); ConsoleLog(tree, time); }
public void GetMove_AlmostInitial_Performance() { var field = Field.Parse(@" 0,0,0,0,0,0,0; 0,0,0,0,0,0,0; 0,0,0,0,0,0,0; 0,0,0,0,0,0,0; 0,0,0,0,0,0,0; 0,0,0,1,2,0,0"); var tree = new SearchTree(); var time =TimeSpan.FromSeconds(10); var act = tree.GetMove(field, TimeSpan.MaxValue, time); ConsoleLog(tree, time); }
internal static SearchTree GenerateSearchTreeCommon(Dictionary<int, Executable[]> codeByLookup, int min, int max) { if (min == max) { return new SearchTree() { Code = codeByLookup[min] }; } if (min + 1 == max) { SearchTree left = new SearchTree() { Code = codeByLookup[min] }; SearchTree right = new SearchTree() { Code = codeByLookup[max] }; return new SearchTree() { LessThanThis = max, Left = left, Right = right }; } int mid = (min + max + 1) / 2; return new SearchTree() { LessThanThis = mid, Left = GenerateSearchTreeCommon(codeByLookup, min, mid - 1), Right = GenerateSearchTreeCommon(codeByLookup, mid, max) }; }
public void GetMove_WinningOption_1() { var field = Field.Parse(@" 0,0,0,1,0,0,0; 0,0,2,1,0,0,0; 0,0,2,1,0,0,0; 0,0,1,2,0,0,0; 0,0,1,1,1,0,0; 2,0,2,1,2,2,2"); var tree = new SearchTree(); var act = tree.GetMove(field, TimeSpan.MaxValue, TimeSpan.FromSeconds(0.1)); Console.WriteLine(tree.Logger); var exp = (byte)1; Assert.AreEqual(exp, act); }
private void IDNaiveButton_Click(object sender, EventArgs e) { var tree = new SearchTree<Problems.SlidingTilesPuzzle.State>(_currentState); var dfs = new DepthFirstSearcher<Problems.SlidingTilesPuzzle.State, int>( tree, x => x.GetActions(), (x, a) => x.Clone().ApplyAction(a), (x, a) => 1, x => x.IsSolution); var id = new IterativeDeepeningDepthFirstSearch<Problems.SlidingTilesPuzzle.State, int>(dfs); var updateCount = 0; var start = DateTime.Now; Action<bool> updateCounts = (force) => { if (!force && ++updateCount % 10000 > 0) return; NodesGeneratedLabel.Text = "Generated = " + dfs.NodesGeneratedCount + " "; ExpandedNodesLabel.Text = "Expanded = " + dfs.NodesExpandedCount + " "; RetainedNodesLabel.Text = "Retained = " + dfs.NodesRetainedCount + " "; SecondsLabel.Text = DateTime.Now.Subtract(start).TotalSeconds.ToString() + " (next depth = " + dfs.NextCostThreshhold + ")"; _currentState = dfs.CurrentNode.Data; panel1.Invalidate(); Application.DoEvents(); }; dfs.NodeExpanded += (s, a) => updateCounts(false); dfs.NodeGenerated += (s, a) => updateCounts(false); var solution = id.Search(); updateCounts(true); }
public void GetMove_3MovesDone_Performance() { var field = Field.Parse(@" 0,0,0,0,0,0,0; 0,0,0,0,0,0,0; 0,0,0,0,0,0,0; 0,0,0,0,0,0,0; 0,0,0,0,1,0,0; 0,0,0,1,2,0,0"); var tree = new SearchTree(); var act = tree.GetMove(field, TimeSpan.MaxValue, TimeSpan.FromSeconds(10)); Console.WriteLine(tree.Logger); }
private void DfsButton_Click(object sender, EventArgs e) { // Without any I/D or heuristics this is the same as random search var tree = new SearchTree<Problems.SlidingTilesPuzzle.State>(_currentState); var dfs = new DepthFirstSearcher<Problems.SlidingTilesPuzzle.State, int>( tree, x => x.GetActions().RandomizeOrder(), (x, a) => x.ApplyAction(a), // Don't need to clone because DFS is one way (x, a) => 1, x => x.IsSolution); var updateCount = 0; var start = DateTime.Now; Action<bool> updateCounts = (force) => { if (!force && ++updateCount % 10000 > 0) return; NodesGeneratedLabel.Text = "Generated = " + dfs.NodesGeneratedCount + " "; ExpandedNodesLabel.Text = "Expanded = " + dfs.NodesExpandedCount + " "; RetainedNodesLabel.Text = "Retained = " + dfs.NodesRetainedCount + " "; SecondsLabel.Text = DateTime.Now.Subtract(start).TotalSeconds.ToString(); _currentState = dfs.CurrentNode.Data; panel1.Invalidate(); Application.DoEvents(); }; dfs.NodeExpanded += (s,a) => updateCounts(false); dfs.NodeGenerated += (s, a) => updateCounts(false); var solution = dfs.Search(); updateCounts(true); }
private void ConsoleLog(SearchTree tree, TimeSpan time) { Console.WriteLine(tree.Logger); Console.WriteLine(String.Format("{0:0.00}MNod, {1:0.00}kNod/s {2:0.00}M-trans", tree.Count / 1000000d, tree.Count / time.TotalMilliseconds, tree.Transpositions / 1000000d)); }
public void GetMove_OneColumnLeft_5() { var field = Field.Parse(@" 2,0,1,1,2,1,1 2,0,1,1,1,2,1 1,0,1,2,2,1,1 2,0,2,1,1,2,2 2,0,1,2,2,1,2 1,2,2,1,1,2,2"); var tree = new SearchTree(); var time = TimeSpan.FromSeconds(10); var act = tree.GetMove(field, TimeSpan.MaxValue, time); ConsoleLog(tree, time); var exp = (byte)5; Assert.AreEqual(exp, act); }
public void GetMove_NotInstantLosing_Not5() { var field = Field.Parse(@" 0,0,1,2,1,0,0; 0,0,1,1,2,0,0; 0,0,2,1,2,0,0; 2,0,2,1,2,2,0; 1,2,2,2,1,1,0; 2,1,1,1,2,1,0"); var tree = new SearchTree(); var act = tree.GetMove(field, TimeSpan.MaxValue, TimeSpan.FromSeconds(1000)); Console.WriteLine(tree.Logger); var exp = (byte)5; Assert.AreNotEqual(exp, act); }
public void GetMove_OneOption_3() { var field = Field.Parse(@" 0,0,0,0,0,0,0; 0,0,0,0,0,0,0; 0,0,0,0,0,0,0; 0,0,0,1,0,0,0; 0,0,0,1,0,0,0; 0,0,2,1,2,0,0"); var tree = new SearchTree(); var time = TimeSpan.FromSeconds(2); var act = tree.GetMove(field, TimeSpan.MaxValue, time); ConsoleLog(tree, time); var exp = (byte)3; Assert.AreEqual(exp, act); }
private void button2_Click(object sender, EventArgs e) { var initialState = Enumerable.Range(0, _problem.Size).Select(x => -1).ToArray(); var tree = new SearchTree<Problems.QueensPuzzle.State>(_problem.CreateState(initialState)); var dfs = new DepthFirstSearcher<Problems.QueensPuzzle.State, int>( tree, GetPossibleActions, ApplyAction, (x, a) => 1, x => x.IsSolution); var updateCount = 0; var start = DateTime.Now; Action<bool> updateCounts = (force) => { if (!force && ++updateCount % 10000 > 0) return; NodesGeneratedLabel.Text = "Generated = " + dfs.NodesGeneratedCount + " "; ExpandedNodesLabel.Text = "Expanded = " + dfs.NodesExpandedCount + " "; RetainedNodesLabel.Text = "Retained = " + dfs.NodesRetainedCount + " "; SecondsLabel.Text = DateTime.Now.Subtract(start).TotalSeconds.ToString(); _currentState = dfs.CurrentNode.Data; panel1.Invalidate(); Application.DoEvents(); }; dfs.NodeExpanded += (s,a) => updateCounts(false); dfs.NodeGenerated += (s, a) => updateCounts(false); var solution = dfs.Search(); updateCounts(true); }