/// <summary> /// Executes the move while updating environment. /// </summary> /// <param name="move">The move.</param> /// <param name="x">The x.</param> /// <param name="y">The y.</param> /// <param name="testMap">The test map.</param> private void ExecuteMoveUpdatingEnvironment(Move move, ref int x, ref int y, char[,] map, ref char[,] testMap) { // Move cursor to the new location TreeHelpers.CalculateMove(move, ref x, ref y, this.mapDims[0], this.mapDims[1]); // Determine if our movement would have pushed a crate bool pushCrate = testMap[x, y] == AlgorithmConstants.crate || testMap[x, y] == AlgorithmConstants.filledGoal; // Figure out what the spot I just move from was before we ever started char previous = map[x, y]; // If it was a crate, make it a tile (cuz it was obviously moved) and put a target there if we moved off the 't' char replacement = (previous == AlgorithmConstants.target || previous == AlgorithmConstants.filledGoal) ? AlgorithmConstants.target : AlgorithmConstants.tile; // Put whatever should replace where the crate was testMap[x, y] = replacement; // Move the crate to its new home if (pushCrate) { int x2 = x; int y2 = y; TreeHelpers.CalculateMove(move, ref x2, ref y2, this.mapDims[0], this.mapDims[1]); testMap[x2, y2] = testMap[x2, y2] == AlgorithmConstants.target ? AlgorithmConstants.filledGoal : AlgorithmConstants.crate; } }
private void Validate <T>(int size, BinaryTreeNode <int> expected) where T : IEquatable <T> { var result = Question_4_2.CreateMinimalBinaryTree(Enumerable.Range(0, size).ToArray()); TreeHelpers.AssertBinaryTreesEqual <int>(expected, result); }
private void MoveToRoot(object sender, ExecutedRoutedEventArgs e) { CenterOnVertex(root_control); var sb = TreeHelpers.FindVisualChildByName <System.Windows.Controls.TextBox>(root_control, "SearchTerm"); sb.Focus(); }
public void Question_4_4_BasicCases() { // One node tree var tree = TreeHelpers.CreateBinaryTree(1, null, null); Validate(true, tree); // Two level tree tree = TreeHelpers.CreateBinaryTree(1, 2, 0); Validate(true, tree); // Two node uneven tree. tree = TreeHelpers.CreateBinaryTree( 1, TreeHelpers.CreateBinaryTree(2, new BinaryTreeNode <int>(3), null), null); Validate(false, tree); // Non BST very uneven. var temp1 = TreeHelpers.CreateBinaryTree(0, 1, 2); var temp2 = TreeHelpers.CreateBinaryTree(4, 5, 6); var temp3 = TreeHelpers.CreateBinaryTree(11, temp1, temp2); tree = TreeHelpers.CreateBinaryTree(8, temp3, null); Validate(false, tree); }
public void Question_4_6_BasicCases() { // Single Node tree tests. var tree = TreeHelpers.CreateBinaryTree(1, null, null); Validate(null, tree); // Small tree tests. tree = TreeHelpers.CreateBinaryTree(1, 0, 2); Validate(2, tree); Validate(1, tree.Left); Validate(null, tree.Right); // Large tree tests. tree = TreeHelpers.CreateBinaryTree( data: 4, left: TreeHelpers.CreateBinaryTree( data: 2, left: TreeHelpers.CreateBinaryTree(1, 0, -1), right: new BinaryTreeNode <int>(3)), right: TreeHelpers.CreateBinaryTree(6, 5, 7)); Validate(5, tree); Validate(3, tree.Left); Validate(-1, tree.Left.Left); Validate(4, tree.Left.Right); Validate(7, tree.Right); Validate(6, tree.Right.Left); Validate(null, tree.Right.Right); }
public void Question_4_8_BasicCases() { // Single Node tree tests. var tree = TreeHelpers.CreateBinaryTree(1, null, null); Validate(tree, tree, tree); // Small tree tests. tree = TreeHelpers.CreateBinaryTree(1, 0, 2); Validate(tree, tree, tree.Left); Validate(tree, tree, tree.Right); Validate(tree, tree.Left, tree.Right); Validate(tree, tree.Right, tree.Left); Validate(tree.Right, tree.Right, tree.Right); Validate(tree.Left, tree.Left, tree.Left); // Large tree tests. tree = TreeHelpers.CreateBinaryTree( data: 4, left: TreeHelpers.CreateBinaryTree( data: 2, left: TreeHelpers.CreateBinaryTree(1, 0, -1), right: TreeHelpers.CreateBinaryTree(10, 11, 12)), right: TreeHelpers.CreateBinaryTree(6, 5, 7)); Validate(tree, tree.Left.Left, tree.Right.Right); Validate(tree, tree.Left.Left.Left, tree.Right.Right); Validate(tree, tree.Left.Right, tree.Right.Left); Validate(tree.Left, tree.Left.Left.Left, tree.Left.Right.Right); }
public void Question_4_12_BasicCases() { // Empty tree. BinaryTreeNode <int> tree = null; Validate(0, tree, 2); Validate(0, tree, 0); // Single Node tree tests. tree = TreeHelpers.CreateBinaryTree(0, null, null); Validate(0, tree, 1); Validate(1, tree, 0); // Small tree; tree = TreeHelpers.CreateBinaryTree(1, 0, 2); Validate(2, tree, 1); Validate(1, tree, 0); Validate(1, tree, 2); Validate(1, tree, 3); Validate(0, tree, 4); Validate(0, tree, -1); // Awkward lopsided tree. // 0 // \ // 1 // \ // 2 // ... tree = TreeHelpers.CreateBinaryTreeFromArray(0, 1, 2, 3, 4, 5); Validate(2, tree, 1); Validate(2, tree, 5); Validate(2, tree, 15); Validate(3, tree, 3); Validate(1, tree, 4); Validate(0, tree, 8); // Bigger tree // 3 // / \ // 1 5 // / \ / \ // 2 0 4 6 tree = TreeHelpers.CreateBinaryTreeFromArray <int>(3, 1, 0, 2, 5, 4, 6); Validate(1, tree, 5); Validate(2, tree, 6); Validate(1, tree, 12); Validate(3, tree, 4); Validate(1, tree, 14); Validate(2, tree, 1); Validate(1, tree, 2); }
public void Question_4_5_BasicCases() { // One node tree var tree = TreeHelpers.CreateBinaryTree(1, null, null); Validate(true, tree); // Invalid two node tree tree = TreeHelpers.CreateBinaryTree(1, new BinaryTreeNode <int>(2), null); Validate(false, tree); // Valid two node tree tree = TreeHelpers.CreateBinaryTree(1, null, new BinaryTreeNode <int>(2)); Validate(true, tree); // Valid three node tree tree = TreeHelpers.CreateBinaryTree(1, 0, 2); Validate(true, tree); // Larger invalid tree tree = TreeHelpers.CreateBinaryTree( 1, TreeHelpers.CreateBinaryTree(0, -1, 2), new BinaryTreeNode <int>(3)); Validate(false, tree); // Larger valid tree tree = TreeHelpers.CreateBinaryTree( 1, TreeHelpers.CreateBinaryTree(-1, -2, 0), new BinaryTreeNode <int>(3)); Validate(true, tree); // Even larger invalid tree. var temp1 = TreeHelpers.CreateBinaryTree(1, 0, 2); var temp2 = TreeHelpers.CreateBinaryTree(5, 4, 6); var temp3 = TreeHelpers.CreateBinaryTree(7, temp1, temp2); tree = TreeHelpers.CreateBinaryTree(8, temp3, null); Validate(false, tree); // Even larger valid tree. temp1 = TreeHelpers.CreateBinaryTree(1, 0, 2); temp2 = TreeHelpers.CreateBinaryTree(6, 5, 7); temp3 = TreeHelpers.CreateBinaryTree(4, temp1, temp2); tree = TreeHelpers.CreateBinaryTree(8, temp3, null); Validate(true, tree); }
private void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e) { SearchResult result = (SearchResult)((System.Windows.Controls.DataGridRow)sender).Item; result.Checked = true; FileItem fi = new FileItem { FileName = result.FileName, FullPath = result.FullPath, Extension = result.Extension, RelPath = result.RelPath }; VertexControl sv = TreeHelpers.FindVisualParent <VertexControl>(sender as DataGridRow); AddFileView(fi, sv, (PocVertex)sv.Vertex, result.LineNumber); graph_provider.SaveGraph(); }
/// <summary> /// Executes the move while updating environment. /// </summary> /// <param name="move">The move.</param> /// <param name="x">The x.</param> /// <param name="y">The y.</param> /// <param name="testMap">The test map.</param> public virtual void ExecuteMoveUpdatingEnvironment(Move move, ref int x, ref int y, ref List <int[]> crateLocations) { // Move cursor to the new location TreeHelpers.CalculateMove(move, ref x, ref y, this.mapDims[0], this.mapDims[1]); int childX = x; int childY = y; // Determine if we walked into a crate if (crateLocations.Exists(crate => crate[0] == childX && crate[1] == childY)) { // If so, push the crate. this.PushCrate(move, childX, childY, ref crateLocations); } }
public long Execute(Guid treeGuid, SetParentNodeDto setParentNode) { // Read all tree from storage var nodes = _treeStorage.GetAllNodes(treeGuid); var nodesByGuids = nodes.ToDictionary(n => n.Guid, n => n); // Validates existence of nodes to be updated var toUpdate = new List <NodeDto>(); var notFound = new List <Guid>(); foreach (var nodeGuid in setParentNode.NodeGuids) { if (nodesByGuids.TryGetValue(nodeGuid, out var node)) { toUpdate.Add(node); } else { notFound.Add(nodeGuid); } } // Validates existence of parent node if (!nodesByGuids.TryGetValue(setParentNode.ParentGuid, out var parent)) { notFound.Add(setParentNode.ParentGuid); } if (notFound.Count > 0) { throw new NotFoundException(string.Format("Nodes not found in Tree [{0}] : {1}.", treeGuid, string.Join(", ", notFound.Select(g => $"[{g}]")))); } // Validates absence of cycles var ancestors = TreeHelpers.GetAncestors(nodes, parent, includingSelf: true).ToArray(); var cyclic = toUpdate.Where(n => ancestors.Contains(n)).ToArray(); if (cyclic.Length > 0) { throw new BadRequestException(string.Format("Cycles detected in Tree [{0}] for nodes {1}.", treeGuid, string.Join(", ", cyclic.Select(g => $"[{g.Guid}]")))); } return(_treeStorage.SetParentNode(parent, toUpdate)); }
/// <summary> /// Crawls this instance. /// </summary> /// <returns>The solution if found</returns> /// <remarks>We have to override this so we can synchonize the forward and reverse crawlers</remarks> public override BaseNode Crawl() { if (!this.reversed) { BaseNode solution = null; while ((!this.IsQueueEmpty() || !reverseCrawler.IsQueueEmpty()) && solution == null) { this.EvaluateAndExpandNode(this.PopQueue()); reverseCrawler.Crawl(); // If there exists a node that both crawlers have found where, combined, a solution is found; that is our winner. List <BaseNode> similarNodes = this.ExploredSet.Where(en => reverseCrawler.ExploredSet.Any(rcEn => rcEn.Key == en.Key)).ToList(); foreach (BaseNode similarNode in similarNodes) { foreach (BaseNode possibleSolution in this.reverseCrawler.ExploredSet.Where(en => en.Key == similarNode.Key)) { List <Move> movesToGoal = TreeHelpers.ActionTracker(possibleSolution); movesToGoal.Reverse(); movesToGoal = TreeHelpers.ReflectMoves(movesToGoal); int x = similarNode.X; int y = similarNode.Y; List <int[]> newChildState = new List <int[]>(); similarNode.CrateLocations.ForEach(state => newChildState.Add(new int[] { state[0], state[1] })); this.MoveToCurrentNode(movesToGoal, ref x, ref y, ref newChildState); if (IsWinningState(newChildState)) { return(InvertNodeHeritage(similarNode, possibleSolution.Parent)); } } } } return(solution); } else { // If we are the reversed solution, we just need to take the normal steps and return if we found a solution. // all the Bi-Directional stuff is done in the non-reversed loop. BaseNode reverseSolution; reverseSolution = this.EvaluateAndExpandNode(this.PopQueue()); return(reverseSolution); } }
public void Question_4_10_BasicCases() { // Null tree var t1 = (BinaryTreeNode <int>)null; var t2 = t1; Validate(t1, t2, expected: true); t2 = new BinaryTreeNode <int>(1); Validate(t1, t2, expected: false); // Single Node tree tests. t1 = TreeHelpers.CreateBinaryTree(1, null, null); t2 = (BinaryTreeNode <int>)null; Validate(t1, t2, expected: true); t2 = new BinaryTreeNode <int>(1); Validate(t1, t2, expected: true); t2 = new BinaryTreeNode <int>(2); Validate(t1, t2, expected: false); // Small tree tests. t1 = TreeHelpers.CreateBinaryTree(1, new BinaryTreeNode <int>(0), null); t2 = t1.Left; Validate(t1, t2, expected: true); Validate(t1, new BinaryTreeNode <int>(4), expected: false); Validate(t1, TreeHelpers.CreateBinaryTree(1, 0, 0), expected: false); t2 = TreeHelpers.CreateBinaryTree(1, new BinaryTreeNode <int>(0), null); Validate(t1, t2, expected: true); // Larger tree tests t1 = TreeHelpers.CreateBinaryTree(9, new BinaryTreeNode <int>(8), t1); t2 = TreeHelpers.CreateBinaryTree(9, new BinaryTreeNode <int>(8), t2); Validate(t1, t2, expected: true); Validate(t1, t2.Left, expected: true); Validate(t1, t2.Right, expected: true); Validate(t1, t2.Right.Right, expected: true); Validate(t1, TreeHelpers.CreateBinaryTree(8, new BinaryTreeNode <int>(9), null), expected: false); // Medium tree tests t1 = TreeHelpers.CreateBinaryTree( data: 4, left: TreeHelpers.CreateBinaryTree(2, 1, 10), right: TreeHelpers.CreateBinaryTree(6, 5, 7)); t2 = TreeHelpers.CreateBinaryTree(2, 1, 10); Validate(t1, t2, expected: true); Validate(t1, TreeHelpers.CreateBinaryTree(5, 6, 7), expected: false); }
private static void element_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { var element = (UIElement)sender; // find the ReoderListBox parent of the element var reorderListBox = TreeHelpers.FindParent <ReorderListBox>(element); if (reorderListBox != null) { // find the ItemContainer FrameworkElement f = TreeHelpers.GetItemContainerFromChildElement(reorderListBox, element) as FrameworkElement; if (f != null) { reorderListBox.BeginDrag(f); } } }
/// <summary> /// Evaluates the move. /// </summary> /// <param name="move">The move.</param> /// <param name="x">The x.</param> /// <param name="y">The y.</param> /// <param name="testMap">The test map.</param> /// <returns>The state of the next node after a move</returns> private State EvaluateMove(Move move, int x, int y, char[,] testMap) { // Given a current location and action or "Move", determine our new x & y and return if we are inbounds or not bool inbounds = TreeHelpers.CalculateMove(move, ref x, ref y, this.mapDims[0], this.mapDims[1]); // If out of bounds return that this is an invalid movement if (!inbounds) { return(State.Invalid); } // If in bounds, return the validity of the move based on if you walking into walks, crates, crates in-front of walls, etc. switch (testMap[x, y]) { case AlgorithmConstants.tile: return(State.Queued); case AlgorithmConstants.filledGoal: case AlgorithmConstants.crate: inbounds = TreeHelpers.CalculateMove(move, ref x, ref y, this.mapDims[0], this.mapDims[1]); if (!inbounds) { return(State.Invalid); } switch (testMap[x, y]) { case AlgorithmConstants.tile: case AlgorithmConstants.target: return(State.Queued); default: return(State.Invalid); } case AlgorithmConstants.wall: return(State.Invalid); case AlgorithmConstants.target: return(State.Goal); default: return(State.Invalid); } }
/// <summary> /// Evaluates the move. /// </summary> /// <param name="move">The move.</param> /// <param name="node">The node.</param> /// <param name="crateMoved">if set to <c>true</c> [crate moved].</param> /// <returns> /// If the move is valid and if a crate was moved /// </returns> public bool MoveIsValid(Move move, BaseNode node, out bool crateMoved) { crateMoved = false; int x = node.X; int y = node.Y; List <int[]> crateLocations = new List <int[]>(); node.CrateLocations.ForEach(crate => crateLocations.Add(new int[] { crate[0], crate[1] })); // Given a current location and action or "Move", determine our new x & y and return if we are inbounds or not bool inbounds = TreeHelpers.CalculateMove(move, ref x, ref y, this.mapDims[0], this.mapDims[1]); // If out of bounds return that this is an invalid movement if (!inbounds) { return(false); } // If we walked into a crate if (node.CrateLocations.Exists(crate => crate[0] == x && crate[1] == y)) { // Push the crate and see if it moved crateMoved = this.PushCrate(move, x, y, ref crateLocations); // If the crate moved, this is a valid move, if it didn't this isn't valid if (crateMoved) { return(true); } else { return(false); } } // We know our movement is in bounds and not into a crate; make sure it isn't into a wall if (this.map[x, y] == wall) { return(false); } // We didn't walk into a crate, a wall, or out of bounds so this move must be valid. return(true); }
async private void TestEditor_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) { if (e.Key == System.Windows.Input.Key.S && !((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)) // Not doing ctrl-s to save { string selected_text = ""; TextArea textarea = e.OriginalSource as TextArea; VertexControl sv = TreeHelpers.FindVisualParent <VertexControl>(textarea); PocVertex source_vertex = (PocVertex)sv.Vertex; selected_text = textarea.Selection.GetText(); await SearchForString(selected_text, sv); } else if (e.Key == System.Windows.Input.Key.N && !((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)) // Not doing ctrl-n for new project { string selected_text = ""; string link_text = ""; TextArea textarea = e.OriginalSource as TextArea; var texteditor = Utils.TreeHelpers.FindVisualParent <TextEditor>(textarea); VertexControl sv = TreeHelpers.FindVisualParent <VertexControl>(textarea); FileVertex source_vertex = (FileVertex)sv.Vertex; selected_text = textarea.Selection.GetText(); var no_lines = 0; var start_line = ""; if (textarea.Selection.EndPosition.Line < textarea.Selection.StartPosition.Line) { no_lines = textarea.Selection.StartPosition.Line - textarea.Selection.EndPosition.Line + 1; start_line = textarea.Selection.EndPosition.Location.ToString(); } else { no_lines = textarea.Selection.EndPosition.Line - textarea.Selection.StartPosition.Line + 1; start_line = textarea.Selection.StartPosition.Location.ToString(); } link_text = source_vertex.ID.ToString() + ":" + source_vertex.FileName + ":" + start_line + ":" + no_lines.ToString(); NotesEditor.TextArea.Document.Text += "\n\n"; NotesEditor.TextArea.Document.Text += link_text + "\n"; NotesEditor.TextArea.Document.Text += selected_text; NotesEditor.TextArea.Document.Text += "\n\n"; NotesEditor.ScrollToEnd(); graph_provider.SaveNotes(); } }
private void NotesEditor_MouseDown(object sender, MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Left && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) { // Ctrl+Click Go to notes var position = NotesEditor.GetPositionFromPoint(e.GetPosition(NotesEditor.TextArea.TextView)); if (position != null) { // Get the line clicked. var clicked_line_no = position.Value.Line; var line_offset = NotesEditor.Document.GetLineByNumber(clicked_line_no); var line = NotesEditor.Document.GetText(line_offset.Offset, line_offset.Length); // Check if there is a link in the line: check with regex if (Regex.IsMatch(line, notes_link_regex)) { // Check if click is within link (if there is one). // Parse link and move to vertex. var match_object = Regex.Match(line, notes_link_regex); var vert_id = int.Parse(match_object.Groups["vertex_id"].Value); var file_name = match_object.Groups["file_name"].Value; var line_no = int.Parse(match_object.Groups["line_no"].Value); var no_lines = int.Parse(match_object.Groups["no_lines"].Value); var vertex = graph_provider.GetVertexById(vert_id); VertexControl vc = graph_area.GetAllVertexControls().Where(x => x.Vertex == vertex).FirstOrDefault(); TextEditor te = TreeHelpers.FindVisualChild <TextEditor>((DependencyObject)vc); te.TextArea.TextView.BackgroundRenderers.Add(new HighlightNotesSnippetBackgroundRenderer(te, line_no, no_lines)); te.ScrollToLine(line_no); Expander ex = TreeHelpers.FindVisualParent <Expander>(te); if (!ex.IsExpanded) { ex.IsExpanded = true; } CenterOnVertex(vc); } } e.Handled = true; } }
/// <summary> /// Calculates the results. /// </summary> /// <param name="solution">The solution.</param> /// <returns>The results of the exploration</returns> private string[] CalculateResults(BaseNode solution) { if (solution == null) { return new[] { "Failure. No solution found." } } ; List <string> compiledFinalState = new List <string>(); string elapsedTime = this.ElapsedTime.ToString(); List <Move> movesToSolution = TreeHelpers.ActionTracker(solution); string numberOfMoves = movesToSolution.Count.ToString(); string moveBreakdown = movesToSolution.Aggregate(string.Empty, (current, move) => current + move.ToString()); string prettyDims = this.mapDims[0] + " " + this.mapDims[1]; compiledFinalState.Add(elapsedTime); compiledFinalState.Add(numberOfMoves); compiledFinalState.Add(moveBreakdown); compiledFinalState.Add(prettyDims); compiledFinalState.Add(solution.Key); // Put the crates in the map for display foreach (int[] crate in solution.CrateLocations) { this.map[crate[0], crate[1]] = AlgorithmConstants.crate; } for (int row = 0; row < this.mapDims[1]; row++) { string temp = string.Empty; for (int column = 0; column < this.mapDims[0]; column++) { temp += this.map[column, row]; } compiledFinalState.Add(temp); } return(compiledFinalState.ToArray()); } }
private void AddFileView(FileItem file_item, VertexControl source, PocVertex source_vertex, List <int> lines = null) { if (!graph_provider.root_vertex.CtagsRun) { System.Windows.Forms.MessageBox.Show("Ctags is still running, so tags are not available.", "Ctags running", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information); } FileVertex new_vertex = graph_provider.AddFileView(file_item, source_vertex); VertexControl new_vertex_control = new VertexControl(new_vertex) { DataContext = new_vertex }; try { graph_area.AddVertex(new_vertex, new_vertex_control); } catch (GraphX.GX_InvalidDataException) { new_vertex_control = graph_area.GetAllVertexControls().Where(c => c.Vertex == new_vertex).First(); } PocEdge new_edge = new PocEdge(source_vertex, new_vertex); graph_area.InsertEdge(new_edge, new EdgeControl(source, new_vertex_control, new_edge)); graph_area.RelayoutGraph(true); graph_area.UpdateLayout(); centre_on_me = new_vertex_control; ICSharpCode.AvalonEdit.TextEditor editor = TreeHelpers.FindVisualChild <ICSharpCode.AvalonEdit.TextEditor>(new_vertex_control); if (editor != null && editor != NotesEditor) { editor.TextArea.TextView.MouseDown += TestEditor_MouseDown; editor.TextArea.SelectionChanged += TestEditor_SelectionChanged; if (graph_provider.root_vertex.CtagsRun) { editor.TextArea.TextView.LineTransformers.Add(new UnderlineCtagsMatches(graph_provider.root_vertex.CtagsMatches.Keys.ToList())); } if (lines != null) { editor.TextArea.TextView.BackgroundRenderers.Add(new HighlightSearchLineBackgroundRenderer(editor, lines)); editor.ScrollToLine(lines.Min()); } editor.Width = editor.ActualWidth; } }
private void onPreApplyTemplate() { if (!m_appliedTemplate) { m_appliedTemplate = true; DependencyObject source = base.TemplatedParent; if (source is ItemsPresenter) { source = TreeHelpers.FindParent <ItemsControl>(source); } if (source != null) { bindToParentItemsControl(ItemHeightProperty, source); bindToParentItemsControl(ItemWidthProperty, source); } } }
/// <summary> /// Pushes the crate. /// </summary> /// <param name="move">The move.</param> /// <param name="x">The x.</param> /// <param name="y">The y.</param> /// <param name="crates">The crates.</param> /// <returns>True if the crate successfully moved; else false.</returns> public bool PushCrate(Move move, int x, int y, ref List <int[]> crates) { // If we walked into a crate, determine if we can push it int[] pushedCrate = crates.Find(crate => crate[0] == x && crate[1] == y); // Calculate where the crate would need to move to bool inbounds = TreeHelpers.CalculateMove(move, ref x, ref y, this.mapDims[0], this.mapDims[1]); // Make sure crate movement is allowed (i.e. within bounds and not into a wall or crate). bool crateMoved = inbounds && !crates.Exists(crate => crate[0] == x && crate[1] == y) && this.map[x, y] != AlgorithmConstants.wall && !OptimizationService.Instance.Optimizer.IsCrateMoveSubOptimal(x, y); if (crateMoved) { pushedCrate[0] = x; pushedCrate[1] = y; } return(crateMoved); }
public void Question_4_11_BasicCases() { // Single Node tree tests. var tree = TreeHelpers.CreateBinaryTree(0, null, null); Validate(tree); // Small tree; tree = TreeHelpers.CreateBinaryTree(1, 0, 2); Validate(tree); // Awkward tree. tree = TreeHelpers.CreateBinaryTreeFromArray(0, 1, 2, 3, 4, 5); Validate(tree); // Bigger tree tree = TreeHelpers.CreateBinaryTreeFromArray <int>(3, 1, 0, 2, 5, 4, 6); Validate(tree); }
protected override void OnMouseMove(MouseEventArgs e) { if (m_isDragging && m_dragAdorner != null) { // update the position of the adorner var current = e.GetPosition(this); m_dragAdorner.OffsetX = current.X - m_mouseDown.X; m_dragAdorner.OffsetY = current.Y - m_mouseDown.Y; // find the item that we are dragging over var element = this.InputHitTest(new Point(e.GetPosition(this).X, e.GetPosition(this).Y)) as UIElement; if (element != null) { var itemOver = TreeHelpers.GetItemContainerFromChildElement(this, element) as FrameworkElement; if (itemOver != null) { var p = Mouse.GetPosition(itemOver); var q = PointToQuadrant(itemOver, p); if (itemOver != m_lastMouseOverItem || q != m_lastMouseOverQuadrant) { if (q == ReorderQuadrant.BottomLeft || q == ReorderQuadrant.BottomRight) { m_lastMoveOverPlacement = ReorderPlacement.After; } else { m_lastMoveOverPlacement = ReorderPlacement.Before; } PreviewInsert(itemOver, m_lastMoveOverPlacement); m_lastMouseOverItem = itemOver; m_lastMouseOverQuadrant = q; } } } } base.OnMouseMove(e); }
/// <summary> /// Inverts the node heritage. /// </summary> /// <param name="basePath">The base path.</param> /// <param name="invertedPath">The inverted path.</param> /// <returns>The complete path</returns> private BaseNode InvertNodeHeritage(BaseNode basePath, BaseNode invertedPath) { if (invertedPath != null) { BaseNode newInvertedPath = invertedPath.Parent; BaseNode newBasePath = new BaseNode( invertedPath.X, invertedPath.Y, invertedPath.CrateLocations, this.CalculatePathCost(basePath, TreeHelpers.DetermineMove(basePath.X, basePath.Y, invertedPath.X, invertedPath.Y), invertedPath.CrateLocations), this.CalculateHeuristicValue(basePath, TreeHelpers.DetermineMove(basePath.X, basePath.Y, invertedPath.X, invertedPath.Y), invertedPath.CrateLocations), basePath, TreeHelpers.DetermineMove(basePath.X, basePath.Y, invertedPath.X, invertedPath.Y)); return(this.InvertNodeHeritage(newBasePath, newInvertedPath)); } return(basePath); }
private void ExpanderRelayout(object sender, RoutedEventArgs e) { Expander expander = e.Source as Expander; recentre = expander.IsExpanded; VertexControl parent_vertex_control = TreeHelpers.FindVisualParent <VertexControl>(e.Source as Expander); if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) { foreach (PocEdge edge in graph_area.Graph.OutEdges((PocVertex)parent_vertex_control.Vertex)) { VertexControl vc = graph_area.GetAllVertexControls().Where(x => x.Vertex == edge.Target).FirstOrDefault(); var new_expander = TreeHelpers.FindVisualChild <Expander>(vc); if (new_expander != null) { new_expander.IsExpanded = expander.IsExpanded; } } } RelayoutGraph(parent_vertex_control); }
private Task SearchForString(string selected_text, VertexControl from_vertex_control, List <string> extensions_to_search = null) { if (selected_text != null && selected_text != "") { PocVertex from_vertex = (PocVertex)from_vertex_control.Vertex; SearchResultsVertex new_search_results_vertex = graph_provider.PerformSearch(selected_text, from_vertex, extensions_to_search); VertexControl new_search_results_vertex_control = new VertexControl(new_search_results_vertex) { DataContext = new_search_results_vertex }; graph_area.AddVertex(new_search_results_vertex, new_search_results_vertex_control); PocEdge new_edge = new PocEdge((PocVertex)from_vertex_control.Vertex, new_search_results_vertex); graph_area.InsertEdge(new_edge, new EdgeControl(from_vertex_control, new_search_results_vertex_control, new_edge)); graph_area.RelayoutGraph(true); graph_area.UpdateLayout(); centre_on_me = new_search_results_vertex_control; System.Windows.Controls.DataGrid grid = TreeHelpers.FindVisualChild <System.Windows.Controls.DataGrid>(new_search_results_vertex_control); System.Windows.Controls.ProgressBar bar = TreeHelpers.FindVisualChild <System.Windows.Controls.ProgressBar>(new_search_results_vertex_control); if (still_counting) { bar.Maximum = 100; } else { bar.Maximum = directory_count; } var search_progress = new Progress <int>((int some_int) => ReportProgress(bar)); return(graph_provider.PopulateResultsAsync(selected_text, new_search_results_vertex, search_progress)); //bar.Visibility = System.Windows.Visibility.Collapsed; //grid.Visibility = System.Windows.Visibility.Visible; } return(new Task(() => { })); }
/// <summary> /// Moves the is valid. /// </summary> /// <param name="move">The move.</param> /// <param name="node"></param> /// <returns> /// If the move is valid with no regard for if the crate moved /// </returns> public override bool MoveIsValid(AlgorithmConstants.Move move, BaseNode node) { if (!this.reversed) { return(base.MoveIsValid(move, node)); } else { int x = node.X; int y = node.Y; bool inbounds = TreeHelpers.CalculateMove(move, ref x, ref y, this.mapDims[0], this.mapDims[1]); if (inbounds && this.map[x, y] != AlgorithmConstants.wall && !node.CrateLocations.Exists(crate => crate[0] == x && crate[1] == y)) { return(true); } else { return(false); } } }
public void Question_4_3_BasicCases() { // One node tree var tree = TreeHelpers.CreateBinaryTree(1, null, null); var expected = new List <List <int> >() { ListHelpers.CreateList(1) }; Validate(expected, tree); // Two level tree tree = TreeHelpers.CreateBinaryTree(1, 2, 0); expected = new List <List <int> >() { ListHelpers.CreateList(1), ListHelpers.CreateList(2, 0) }; Validate(expected, tree); // Two level tree var temp1 = TreeHelpers.CreateBinaryTree(0, 1, 2); var temp2 = TreeHelpers.CreateBinaryTree(4, 5, 6); var temp3 = TreeHelpers.CreateBinaryTree(11, temp1, temp2); var temp4 = TreeHelpers.CreateBinaryTree(8, temp3, null); expected = new List <List <int> >() { ListHelpers.CreateList(8), ListHelpers.CreateList(11), ListHelpers.CreateList(0, 4), ListHelpers.CreateList(1, 2, 5, 6), }; Validate(expected, temp4); }
public long Execute(Guid treeGuid, DeleteNodesDto deleteNodes) { var nodes = _treeStorage.GetAllNodes(treeGuid); var toDelete = new List <NodeDto>(); var notFound = new List <Guid>(); foreach (var nodeGuid in deleteNodes.NodeGuids) { var node = nodes.FirstOrDefault(n => n.Guid == nodeGuid); if (node == null) { notFound.Add(nodeGuid); } else { toDelete.Add(node); } } if (notFound.Count > 0) { throw new NotFoundException(string.Format("Nodes not found in Tree [{0}] : {1}.", treeGuid, string.Join(", ", notFound.Select(g => $"[{g}]")))); } var subforest = TreeHelpers.GetSubforest(nodes, toDelete); if (!deleteNodes.Recursive && subforest.Length > toDelete.Count) { throw new BadRequestException("Can't delete nodes that have children (use the `Recursive` option)."); } else { return(_treeStorage.DeleteNodes(subforest)); } }