public GVDKarla(ObstacleGrid grid) { this.grid = grid; open = new IntervalHeap<GridCellValue>(); ties = new LinkedList<GridCell>(); dist = new float[grid.NumColumns, grid.NumRows]; distNew = new float[grid.NumColumns, grid.NumRows]; parent = new GridCell[grid.NumColumns, grid.NumRows]; tie = new GridCell[grid.NumColumns, grid.NumRows]; obst = new int[grid.NumColumns, grid.NumRows]; valid = new HashSet<int>(); voro = new bool[grid.NumColumns, grid.NumRows]; for (int c = grid.NumColumns - 1; c >= 0; c--) for (int r = grid.NumRows - 1; r >= 0; r--) { dist[c, r] = float.PositiveInfinity; distNew[c, r] = float.PositiveInfinity; parent[c, r] = GridCell.Unknown; tie[c, r] = GridCell.Unknown; obst[c, r] = -1; voro[c, r] = false; } }
/// <summary> /// Sorts the vertices in topological order /// </summary> /// <returns>List of topological sorted vertices</returns> public List <Vertex> TopologicalSort(ColumnChanges columnChanges) { IPriorityQueue <Vertex> priorityQueue = new IntervalHeap <Vertex>(new VerticesComparer(Options, columnChanges)); var sortedVertices = new List <Vertex>(); var incomingEdges = new Dictionary <Vertex, int>(); foreach (var v in Vertices) { incomingEdges[v] = v.IngoingEdges().Count; if (incomingEdges[v] == 0) { priorityQueue.Add(v); } } while (!priorityQueue.IsEmpty) { Vertex v = priorityQueue.FindMin(); sortedVertices.Add(v); priorityQueue.DeleteMin(); foreach (var e in v.OutgoingEdges()) { incomingEdges[e.Destination]--; if (incomingEdges[e.Destination] == 0) { priorityQueue.Add(e.Destination); } } } return(sortedVertices); }
public static List <Point> FindClosestPoints(Point[] points, int k) { IPriorityQueue <Point> maxHeap = new IntervalHeap <Point>(); // new IPriorityQueueHandle<Point>((p1, p2) => p2.distFromOrigin() - p1.distFromOrigin()); // put first 'k' points in the max heap for (int i = 0; i < k; i++) { maxHeap.Add(points[i]); } // go through the remaining points of the input array, if a point is closer to // the origin than the top point of the max-heap, remove the top point from // heap and add the point from the input array for (int i = k; i < points.Length; i++) { if (points[i].distFromOrigin() < maxHeap.Max().distFromOrigin()) { maxHeap.DeleteMax(); maxHeap.Add(points[i]); } } //Point x = new Point(k, 0); // the heap has 'k' points closest to the origin, return them in a list return(maxHeap.ToList <Point>()); }
public List <S> Find_path(S start, S end) { System.Collections.Generic.HashSet <S> closedSet = new System.Collections.Generic.HashSet <S>(); IntervalHeap <Node> openSet = new IntervalHeap <Node>(); Node curr = new Node(start, null); while (!curr.state.Equals(end)) { if (!closedSet.Contains(curr.state)) { foreach (S state in curr.state.AvailableMoves()) { if (closedSet.Contains(state)) { continue; } openSet.Add(new Node(state, curr)); } closedSet.Add(curr.state); } curr = openSet.DeleteMin(); } Stack <S> stack = new Stack <S>(); while (curr != null) { stack.Push(curr.state); curr = curr.parent; } return(stack.ToList <S>()); }
public static void DikstrasSearch(Node[] nodes, Node source) { var table = new HashDictionary <Node, Entry>(); foreach (var node in nodes) { table.Add(node, new Entry(false, float.MaxValue, null)); } var sourceEntry = table[source]; sourceEntry.cost = 0; table[source] = sourceEntry; var priorityQueue = new IntervalHeap <NodeAndCost>( new DelegateComparer <NodeAndCost>( (nodeAndCost1, nodeAndCost2) => nodeAndCost1.cost.CompareTo(nodeAndCost2.cost))) { new NodeAndCost(source, 0) }; while (!priorityQueue.IsEmpty) { var nodeAndCost = priorityQueue.DeleteMin(); var currentNode = nodeAndCost.node; if (table[currentNode].known) { continue; } var currentNodeEntry = table[currentNode]; currentNodeEntry.known = true; table[currentNode] = currentNodeEntry; foreach (var edge in currentNode.outEdges) { var toNode = edge.ToNode; var toNodeCost = table[currentNode].cost + edge.Cost; if (!(table[toNode].cost > toNodeCost)) { continue; } var toNodeEntry = table[toNode]; toNodeEntry.cost = toNodeCost; toNodeEntry.predecessor = currentNode; table[toNode] = toNodeEntry; priorityQueue.Add(new NodeAndCost(toNode, toNodeCost)); } } foreach (var node in nodes) { _NEXT_NODE_AND_COST_TABLE[new NodePair(source, node)] = ExtractNextNodeFromTable(table, source, node); } }
public virtual AstarNode <T> Solve(AstarNode <T> Root, params object[] args) { IntervalHeap <AstarNode <T> > ih = new IntervalHeap <AstarNode <T> >(); ih.Add(Root); AstarNode <T> curNode; bool add; while (ih.Count > 0) { curNode = ih.DeleteMin(); curNode.Expand(args); if (curNode.Completed(args)) { return(curNode); } if (curNode.Children.Count > 0) { foreach (var node in curNode.Children) { if (node.CanAdd()) { ih.Add(node); added++; } total++; } } } return(null); }
public void RemoveItemsFromHeap() { IntervalHeap <int> h = new IntervalHeap <int>(); for (int i = 0; i < 20; i++) { h.Push(i, i); } h.Remove(10); h.Remove(2); h.Remove(11); h.Remove(9); h.Remove(19); h.Remove(0); Assert.AreEqual(h.Pop(), 18); Assert.AreEqual(h.Pop(), 17); Assert.AreEqual(h.Pop(), 16); Assert.AreEqual(h.Pop(), 15); Assert.AreEqual(h.Pop(), 14); Assert.AreEqual(h.Pop(), 13); Assert.AreEqual(h.Pop(), 12); Assert.AreEqual(h.Pop(), 8); Assert.AreEqual(h.Pop(), 7); Assert.AreEqual(h.Pop(), 6); Assert.AreEqual(h.Pop(), 5); Assert.AreEqual(h.Pop(), 4); Assert.AreEqual(h.Pop(), 3); Assert.AreEqual(h.Pop(), 1); Assert.AreEqual(h.Count, 0); }
public void Replace5a() { for (var size = 0; size < 130; size++) { IPriorityQueue <double> q = new IntervalHeap <double>(); IPriorityQueueHandle <double> handle1 = null; q.Add(ref handle1, 3.0); Assert.AreEqual(3.0, q.FindMin()); for (var i = 1; i < size; i++) { q.Add(i + 3.0); } Assert.AreEqual(3.0, q.FindMin()); for (var min = 2; min >= -10; min--) { Assert.AreEqual(min + 1.0, q.Replace(handle1, min)); Assert.AreEqual(min, q.FindMin()); } Assert.AreEqual(-10.0, q.DeleteMin()); for (var i = 1; i < size; i++) { Assert.AreEqual(i + 3.0, q.DeleteMin()); } Assert.IsTrue(q.IsEmpty); } }
/// <summary> /// The Interval heap used in this method represents the min heap /// required form the last sub task of task 7.37. /// </summary> /// <param name="array"></param> /// <param name="kSmallestElement"></param> /// <returns></returns> public int FindKthSmallestElementUsingMinHeap(int[] array, int kSmallestElement) { var n = array.Length; if (n - 1 < kSmallestElement) { return(int.MinValue); } IntervalHeap <int> intervalHeap = new IntervalHeap <int>(); for (int i = 0; i < n; i++) { if (intervalHeap.Count < kSmallestElement) { intervalHeap.Add(array[i]); } else { if (intervalHeap.FindMax() > array[i]) { intervalHeap.DeleteMax(); intervalHeap.Add(array[i]); } } } for (int i = 0; i < kSmallestElement - 1; i++) { intervalHeap.DeleteMin(); } return(intervalHeap.FindMin()); }
/// <summary> /// Construct a new nearest neighbour iterator. /// </summary> /// <param name="pRoot">The root of the tree to begin searching from.</param> /// <param name="tSearchPoint">The point in n-dimensional space to search.</param> /// <param name="kDistance">The distance function used to evaluate the points.</param> /// <param name="iMaxPoints">The max number of points which can be returned by this iterator. Capped to max in tree.</param> /// <param name="fThreshold">Threshold to apply to the search space. Negative numbers indicate that no threshold is applied.</param> public NearestNeighbour(KDNode <T> pRoot, double[] tSearchPoint, DistanceFunctions kDistance, int iMaxPoints, double fThreshold) { // Check the dimensionality of the search point. if (tSearchPoint.Length != pRoot.iDimensions) { throw new Exception("Dimensionality of search point and kd-tree are not the same."); } // Store the search point. this.tSearchPoint = new double[tSearchPoint.Length]; Array.Copy(tSearchPoint, this.tSearchPoint, tSearchPoint.Length); // Store the point count, distance function and tree root. iPointsRemaining = Math.Min(iMaxPoints, pRoot.Size); this.fThreshold = fThreshold; kDistanceFunction = kDistance; this.pRoot = pRoot; iMaxPointsReturned = iMaxPoints; _CurrentDistance = -1; // Create an interval heap for the points we check. pEvaluated = new IntervalHeap <T>(); // Create a min heap for the things we need to check. pPending = new MinHeap <KDNode <T> >(); pPending.Insert(0, pRoot); }
private void GetTopDistances(IEnumerable <string> threadDictionary) { var comparer = new WordDistanceComparer(); var heap = new IntervalHeap <WordDistance>(HeapCapacity, comparer); foreach (var entry in threadDictionary) { var threshold = heap.Any() ? heap.FindMax().Distance : int.MaxValue; var distance = Value.GetDistance(entry, threshold); if (heap.Count < HeapCapacity) { heap.Add(new WordDistance(entry, distance)); continue; } if (distance >= threshold) { continue; } heap.DeleteMax(); heap.Add(new WordDistance(entry, distance)); } foreach (var wordDistance in heap) { results.Add(wordDistance); } }
public void Replace5b() { for (var size = 0; size < 130; size++) { IPriorityQueue <double> q = new IntervalHeap <double>(); IPriorityQueueHandle <double> handle1 = null; q.Add(ref handle1, -3.0); Assert.AreEqual(-3.0, q.FindMax()); for (var i = 1; i < size; i++) { q.Add(-i - 3.0); } Assert.AreEqual(-3.0, q.FindMax()); for (var max = -2; max <= 10; max++) { Assert.AreEqual(max - 1.0, q.Replace(handle1, max)); Assert.AreEqual(max, q.FindMax()); } Assert.AreEqual(10.0, q.DeleteMax()); for (var i = 1; i < size; i++) { Assert.AreEqual(-i - 3.0, q.DeleteMax()); } Assert.IsTrue(q.IsEmpty); } }
public void Bug20130208() { IPriorityQueue <double> q = new IntervalHeap <double>(); IPriorityQueueHandle <double> h0 = null, h2 = null, h4 = null, h7 = null, h5 = null; // Add(43, 0); q.Add(ref h0, 43); // Remove(); q.DeleteMin(); // XAddMaxReplace(9, 2); q.Add(ref h2, Double.MaxValue); q[h2] = 9; // XAddMaxReplace(32, 4); q.Add(ref h4, Double.MaxValue); q[h4] = 32; // XAddMaxReplace(44, 7); q.Add(ref h7, Double.MaxValue); q[h7] = 44; // Remove(); q.DeleteMin(); // XAddMaxReplace(0, 5); q.Add(ref h5, Double.MaxValue); q[h5] = 0; // Internally inconsistent data structure already now Assert.IsTrue(q.Check()); }
private static void addToFrontier(CytoscapeMap map, IntervalHeap <CytoscapeNode> frontier, CytoscapeNode node) { CytoscapeNode tempNode; foreach (CytoscapeConnection connection in node.connections) { int undirectedTargetID = connection.undirectedTarget(node); tempNode = map.getNode(undirectedTargetID); // Discard cyclic paths if (!node.hasVisitedNode(undirectedTargetID)) { // Keep track of the path taken if (node.path == null || !node.path.Any()) { node.path = new List <CytoscapeNode>(); node.path.Add(node); } // Make sure to be duplicating the path instead of pointing at node's path field tempNode.path = new List <CytoscapeNode>(node.path); tempNode.path.Add(tempNode); // f is the heuristic plus the distance traveled so far tempNode.distance = node.distance + connection.distance; tempNode.f = tempNode.heuristic + tempNode.distance; frontier.Add(tempNode); } } }
//HELPERS protected override NetworkInterface getRoute(Node destination) { IntervalHeap <NodeEntry> sortedNodes = new IntervalHeap <NodeEntry>(); HashDictionary <Node, NodeEntry> hashedNodes = new HashDictionary <Node, NodeEntry>(); NodeEntry thisNode = new NodeEntry(); thisNode.Node = node; thisNode.Time = Timer.CurrentTime; bool added = sortedNodes.Add(ref thisNode.Handle, thisNode); NodeEntry temp; bool found = sortedNodes.Find(thisNode.Handle, out temp); Debug.Assert(found); Debug.Assert(added); hashedNodes.Add(node, thisNode); double currentTime = -1; while (sortedNodes.Count > 0) { NodeEntry current = sortedNodes.DeleteMin(); Debug.Assert(current.Time >= currentTime); currentTime = current.Time; if (current.Node == destination) { return(extractInterface(current, hashedNodes)); } nextMove(current, sortedNodes, hashedNodes); Debug.Assert(sortedNodes.Check()); } //route not found return(null); }
public GVDKarla(ObstacleGrid grid) { this.grid = grid; open = new IntervalHeap <GridCellValue>(); ties = new LinkedList <GridCell>(); dist = new float[grid.NumColumns, grid.NumRows]; distNew = new float[grid.NumColumns, grid.NumRows]; parent = new GridCell[grid.NumColumns, grid.NumRows]; tie = new GridCell[grid.NumColumns, grid.NumRows]; obst = new int[grid.NumColumns, grid.NumRows]; valid = new HashSet <int>(); voro = new bool[grid.NumColumns, grid.NumRows]; for (int c = grid.NumColumns - 1; c >= 0; c--) { for (int r = grid.NumRows - 1; r >= 0; r--) { dist[c, r] = float.PositiveInfinity; distNew[c, r] = float.PositiveInfinity; parent[c, r] = GridCell.Unknown; tie[c, r] = GridCell.Unknown; obst[c, r] = -1; voro[c, r] = false; } } }
/// <summary> /// Dijkstra. Attempts to find the shortest path from start to end, only using pixels inside the "border pixel" collection that was discovered in FloodFill() <see cref="FloodFill"/> /// </summary> /// <param name="start"></param> /// <param name="end"></param> /// <returns></returns> private System.Collections.Generic.IList <Point> LeastCostPath(Point start, Point end) { var h = new IntervalHeap <Node>(new NodeCmpr()); var n = new Node { Back = null, Cost = 0, Point = start }; h.Add(n); _considered = new PixelTracker(_image.Width, _image.Height) { OutsideDefault = true }; while (!h.IsEmpty) { var node = h.DeleteMin(); if (node.Point.X == end.X && node.Point.Y == end.Y) { return(Backtrace(node)); } Follow(h, node, node.Point.X - 1, node.Point.Y - 1); Follow(h, node, node.Point.X - 1, node.Point.Y); Follow(h, node, node.Point.X - 1, node.Point.Y + 1); Follow(h, node, node.Point.X, node.Point.Y + 1); Follow(h, node, node.Point.X + 1, node.Point.Y + 1); Follow(h, node, node.Point.X + 1, node.Point.Y); Follow(h, node, node.Point.X + 1, node.Point.Y - 1); Follow(h, node, node.Point.X, node.Point.Y - 1); } return(new Point[] {}); }
public JumpPointParam(BaseGrid iGrid, GridPos iStartPos, GridPos iEndPos, DiagonalMovement iDiagonalMovement = DiagonalMovement.Always, HeuristicMode iMode = HeuristicMode.EUCLIDEAN) : base(iGrid, iStartPos, iEndPos, iDiagonalMovement, iMode) { openList = new IntervalHeap <Node>(); CurIterationType = IterationType.LOOP; }
public void Init() { heap = new IntervalHeap<int>(); for(int i = 0; i < heap_data.Length; i++) { heap_data[i] = i; } }
public ListNode mergeKLists(List <ListNode> a) { if (a == null || a.Count == 0) { return(null); } var pq = new IntervalHeap <ListNode>(); foreach (var ln in a) { if (ln != null) { pq.Add(ln); } } var head = new ListNode(0); var p = head; while (pq.Count > 0) { var t = pq.DeleteMin(); p.next = t; p = p.next; if (t.next != null) { pq.Add(t.next); } } return(head.next); }
public override void Update(Pose goal) { bool[,] expanded = new bool[grid.NumColumns, grid.NumRows]; LinkedList <GridCell>[,] memoized = new LinkedList <GridCell> [grid.NumColumns, grid.NumRows]; GridCell startCell = grid.PointToCellPosition(goal.Position); IntervalHeap <GridCellValue> open = new IntervalHeap <GridCellValue>(); for (int c = 0; c < grid.NumColumns; c++) { for (int r = 0; r < grid.NumRows; r++) { heuristic[c, r] = float.PositiveInfinity; expanded[c, r] = false; } } heuristic[startCell.C, startCell.R] = 0f; open.Add(new GridCellValue(startCell, 0f)); while (!open.IsEmpty) { GridCell cell = open.DeleteMin().Position; expanded[cell.C, cell.R] = true; LinkedList <GridCell> neighbors = memoized[cell.C, cell.R]; if (neighbors == null) { neighbors = grid.Get8Neighbors(cell); memoized[cell.C, cell.R] = neighbors; } foreach (GridCell n in neighbors) { if (expanded[n.C, n.R]) { continue; } if (grid.OccupiedCells[n.C, n.R] > 0) { continue; } if (grid.GVD.GetObstacleDistance(n) <= Car.HALF_CAR_WIDTH) { continue; } float dist = cell.C == n.C || cell.R == n.R ? 1f : sqrt2; dist += heuristic[cell.C, cell.R]; if (dist < heuristic[n.C, n.R]) { heuristic[n.C, n.R] = dist; open.Add(new GridCellValue(n, dist)); } } } }
public JumpPointParam(BaseGrid grid, EndNodeUnWalkableTreatment allowEndNodeUnWalkable = EndNodeUnWalkableTreatment.Allow, DiagonalMovement diagonalMovement = DiagonalMovement.Always, HeuristicMode mode = HeuristicMode.Euclidean) : base(grid, diagonalMovement, mode) { CurEndNodeUnWalkableTreatment = allowEndNodeUnWalkable; OpenList = new IntervalHeap <Node>(); CurIterationType = IterationType.Loop; }
public JumpPointParam(BaseGrid iGrid, EndNodeUnWalkableTreatment iAllowEndNodeUnWalkable = EndNodeUnWalkableTreatment.ALLOW, HeuristicMode iMode = HeuristicMode.EUCLIDEAN) : base(iGrid, iMode) { CurEndNodeUnWalkableTreatment = iAllowEndNodeUnWalkable; openList = new IntervalHeap <Node>(); CurIterationType = IterationType.LOOP; }
public JumpPointParam(BaseGrid iGrid, GridPos iStartPos, GridPos iEndPos, bool iAllowEndNodeUnWalkable = true, HeuristicMode iMode = HeuristicMode.EUCLIDEAN) : base(iGrid, iStartPos, iEndPos, iMode) { CurEndNodeUnWalkableTreatment = iAllowEndNodeUnWalkable ? EndNodeUnWalkableTreatment.ALLOW : EndNodeUnWalkableTreatment.DISALLOW; openList = new IntervalHeap <Node>(); CurIterationType = IterationType.LOOP; }
public void Init() { heap = new IntervalHeap <int>(); for (int i = 0; i < heap_data.Length; i++) { heap_data[i] = i; } }
public JumpPointParam(BaseGrid iGrid, GridPos iStartPos, GridPos iEndPos, EndNodeUnWalkableTreatment iAllowEndNodeUnWalkable = EndNodeUnWalkableTreatment.Allow, DiagonalMovement iDiagonalMovement = DiagonalMovement.Always, HeuristicMode iMode = HeuristicMode.Euclidean) : base(iGrid, iStartPos, iEndPos, iDiagonalMovement, iMode) { CurEndNodeUnWalkableTreatment = iAllowEndNodeUnWalkable; openList = new IntervalHeap <Node>(); CurIterationType = IterationType.Loop; }
public void Init() { _heap = new IntervalHeap <ECaseContent>(); Vector2[] array = new Vector2[100]; //Array.Clear(); }
/// <param name="intPairComparer">Comparer for two positions passed in function arguments: x1, y1, x2, y2.</param> public PriorityPositionQueue(Func <int, int, int, int, int> intPairComparer) { Func <Position, Position, int> positionComparerFunction = (first, second) => intPairComparer(first.X, first.Y, second.X, second.Y); var positionComparer = new FunctionalComparer <Position>(positionComparerFunction); _intervalHeap = new IntervalHeap <Position>(positionComparer); }
public StrikingDummy(string name = "Fluffy Pillow", long maxHP = long.MaxValue) { Name = name; MaxHP = maxHP; CurrentHP = MaxHP; Auras = new IntervalHeap <Aura>(); }
public void getMovementPaths(Vector2 startPosition, int moveDistance, bool highlight) { //Get no go areas from player controllers var unitPositions = Controller.getUnitPositions(); // Pathfinding stuff IntervalHeap <PathfinderNode> frontier = new IntervalHeap <PathfinderNode>(new PathfinderNode(new Vector2(), 0)); frontier.Add(new PathfinderNode(startPosition, 0)); Dictionary <Vector2, Vector2> cameFrom = new Dictionary <Vector2, Vector2>(); Dictionary <Vector2, int> costSoFar = new Dictionary <Vector2, int>(); cameFrom.Add(startPosition, new Vector2(-1, -1)); costSoFar.Add(startPosition, 0); while (frontier.Count > 0) { //Get current PathfinderNode current = frontier.FindMin(); frontier.DeleteMin(); // iterate through neighbours foreach (Vector2 next in map.getNeibour(current.position)) { if (unitPositions.Contains(next)) { continue; } int newCost = map.tileTypes[map.tiles[(int)next.x, (int)next.y]].cost + costSoFar[current.position]; if (newCost <= moveDistance && (!costSoFar.ContainsKey(next) || newCost < costSoFar[next])) { int priority = newCost; if (costSoFar.ContainsKey(next)) { costSoFar[next] = newCost; PathfinderNode newNode = new PathfinderNode(next, priority); frontier.Add(newNode); cameFrom[next] = current.position; } else { costSoFar.Add(next, newCost); PathfinderNode newNode = new PathfinderNode(next, priority); frontier.Add(newNode); cameFrom.Add(next, current.position); } } } } if (highlight) { map.highlightArea(new List <Vector2>(costSoFar.Keys), new Color(0, 1, 1)); } pathingData = cameFrom; }
public void PriorityMinEdgeFindsFirst() { IPriorityQueue <WeightedEdge <int> > queue = new IntervalHeap <WeightedEdge <int> >(); queue.Add(new WeightedEdge <int>(0, 1, 1)); queue.Add(new WeightedEdge <int>(1, 2, Double.PositiveInfinity)); Assert.AreEqual(new WeightedEdge <int>(0, 1, 1), queue.FindMin()); }
private static void identifySuccessors(JumpPointParam iParam, Node iNode) { HeuristicDelegate tHeuristic = iParam.HeuristicFunc; IntervalHeap <Node> tOpenList = iParam.openList; int tEndX = iParam.EndNode.x; int tEndY = iParam.EndNode.y; GridPos tNeighbor; GridPos tJumpPoint; Node tJumpNode; List <GridPos> tNeighbors = findNeighbors(iParam, iNode); for (int i = 0; i < tNeighbors.Count; i++) { tNeighbor = tNeighbors[i]; if (iParam.UseRecursive) { tJumpPoint = jump(iParam, tNeighbor.x, tNeighbor.y, iNode.x, iNode.y); } else { tJumpPoint = jumpLoop(iParam, tNeighbor.x, tNeighbor.y, iNode.x, iNode.y); } if (tJumpPoint != null) { tJumpNode = iParam.SearchGrid.GetNodeAt(tJumpPoint.x, tJumpPoint.y); if (tJumpNode == null) { if (iParam.EndNode.x == tJumpPoint.x && iParam.EndNode.y == tJumpPoint.y) { tJumpNode = iParam.SearchGrid.GetNodeAt(tJumpPoint); } } if (tJumpNode.isClosed) { continue; } // include distance, as parent may not be immediately adjacent: float tCurNodeToJumpNodeLen = tHeuristic(Math.Abs(tJumpPoint.x - iNode.x), Math.Abs(tJumpPoint.y - iNode.y)); float tStartToJumpNodeLen = iNode.startToCurNodeLen + tCurNodeToJumpNodeLen; // next `startToCurNodeLen` value if (!tJumpNode.isOpened || tStartToJumpNodeLen < tJumpNode.startToCurNodeLen) { tJumpNode.startToCurNodeLen = tStartToJumpNodeLen; tJumpNode.heuristicCurNodeToEndLen = (tJumpNode.heuristicCurNodeToEndLen == null ? tHeuristic(Math.Abs(tJumpPoint.x - tEndX), Math.Abs(tJumpPoint.y - tEndY)) : tJumpNode.heuristicCurNodeToEndLen); tJumpNode.heuristicStartToEndLen = tJumpNode.startToCurNodeLen + tJumpNode.heuristicCurNodeToEndLen.Value; tJumpNode.parent = iNode; if (!tJumpNode.isOpened) { tOpenList.Add(tJumpNode); tJumpNode.isOpened = true; } } } } }
/// public virtual System.Collections.Generic.IList<Tuple<int, float>> Recommend( int user_id, int n = -1, System.Collections.Generic.ICollection<int> ignore_items = null, System.Collections.Generic.ICollection<int> candidate_items = null) { if (candidate_items == null) candidate_items = Enumerable.Range(0, MaxItemID - 1).ToList(); if (ignore_items == null) ignore_items = new int[0]; System.Collections.Generic.IList<Tuple<int, float>> ordered_items; if (n == -1) { var scored_items = new List<Tuple<int, float>>(); foreach (int item_id in candidate_items) if (!ignore_items.Contains(item_id)) { float score = Predict(user_id, item_id); if (score > float.MinValue) scored_items.Add(Tuple.Create(item_id, score)); } ordered_items = scored_items.OrderByDescending(x => x.Item2).ToArray(); } else { var comparer = new DelegateComparer<Tuple<int, float>>( (a, b) => a.Item2.CompareTo(b.Item2) ); var heap = new IntervalHeap<Tuple<int, float>>(n, comparer); float min_relevant_score = float.MinValue; foreach (int item_id in candidate_items) if (!ignore_items.Contains(item_id)) { float score = Predict(user_id, item_id); if (score > min_relevant_score) { heap.Add(Tuple.Create(item_id, score)); if (heap.Count > n) { heap.DeleteMin(); min_relevant_score = heap.FindMin().Item2; } } } ordered_items = new Tuple<int, float>[heap.Count]; for (int i = 0; i < ordered_items.Count; i++) ordered_items[i] = heap.DeleteMax(); } return ordered_items; }
public List<Node> AStarSearch(Vector3 start, Vector3 end) { var frontier = new IntervalHeap<Node>(new NodeComparer()); var cameFrom = new Dictionary<string, Node>(); //var costSoFar = new Dictionary<string, int>(); var startNode = FindNode(start); var endNode = FindNode(end); frontier.Add(startNode); cameFrom.Add(startNode.ToString(), null); while (frontier.Any()) { var currentNode = frontier.FindMin(); frontier.DeleteMin(); if (currentNode == endNode) break; foreach (var neighbor in currentNode.Neighboors) { var neighborName = neighbor.ToString(); if (cameFrom.ContainsKey(neighborName)) continue; var newCost = Heuristic(endNode, neighbor); neighbor.Cost = newCost; frontier.Add(neighbor); cameFrom.Add(neighborName, currentNode); } } var current = endNode; var path = new List<Node> { current }; if (!cameFrom.ContainsKey(endNode.ToString())) return path; while (current != startNode) { if (!cameFrom.ContainsKey(current.ToString())) continue; current = cameFrom[current.ToString()]; path.Add(current); } return path; }
static void Main() { var people = new IntervalHeap<Person>(); people.Add(new Person("Nakov", 25)); people.Add(new Person("Petya", 24)); people.Add(new Person("Pesho", 25)); people.Add(new Person("Maria", 22)); people.Add(new Person("Ivan", -1)); Console.WriteLine("Min: {0}", people.FindMin()); Console.WriteLine("Max: {0}", people.FindMax()); while (people.Count > 0) { Console.WriteLine(people.DeleteMin()); } }
public Grid(int width, int height) { m_world = Matrix.Identity; m_width = width; m_height = height; m_capacity = width * height; m_grid = new List<Cell>(m_capacity); for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) m_grid.Add(new Cell(new Point(x, y))); m_open = new IntervalHeap<Cell>(m_capacity, new CellComparer()); m_closed = new List<Cell>(m_capacity); }
/// <summary>Score items for a given user</summary> /// <param name="recommender">the recommender to use</param> /// <param name="user_id">the numerical ID of the user</param> /// <param name="candidate_items">a collection of numerical IDs of candidate items</param> /// <param name="n">number of items to return (optional)</param> /// <returns>a list of pairs, each pair consisting of the item ID and the predicted score</returns> public static System.Collections.Generic.IList<Pair<int, float>> ScoreItems(this IRecommender recommender, int user_id, System.Collections.Generic.IList<int> candidate_items, int n = -1) { if (n == -1) { var result = new Pair<int, float>[candidate_items.Count]; for (int i = 0; i < candidate_items.Count; i++) { int item_id = candidate_items[i]; result[i] = new Pair<int, float>(item_id, recommender.Predict(user_id, item_id)); } return result; } else { var comparer = new DelegateComparer<Pair<int, float>>( (a, b) => a.Second.CompareTo(b.Second) ); var heap = new IntervalHeap<Pair<int, float>>(n, comparer); float min_relevant_score = float.MinValue; foreach (int item_id in candidate_items) { float score = recommender.Predict(user_id, item_id); if (score > min_relevant_score) { heap.Add(new Pair<int, float>(item_id, score)); if (heap.Count > n) { heap.DeleteMin(); min_relevant_score = heap.FindMin().Second; } } } var result = new Pair<int, float>[heap.Count]; for (int i = 0; i < result.Length; i++) result[i] = heap.DeleteMax(); return result; } }
public override void Update(Pose goal) { bool[,] expanded = new bool[grid.NumColumns, grid.NumRows]; LinkedList<GridCell>[,] memoized = new LinkedList<GridCell>[grid.NumColumns, grid.NumRows]; GridCell startCell = grid.PointToCellPosition(goal.Position); IntervalHeap<GridCellValue> open = new IntervalHeap<GridCellValue>(); for (int c = 0; c < grid.NumColumns; c++) for (int r = 0; r < grid.NumRows; r++) { heuristic[c, r] = float.PositiveInfinity; expanded[c, r] = false; } heuristic[startCell.C, startCell.R] = 0f; open.Add(new GridCellValue(startCell, 0f)); while (!open.IsEmpty) { GridCell cell = open.DeleteMin().Position; expanded[cell.C, cell.R] = true; LinkedList<GridCell> neighbors = memoized[cell.C, cell.R]; if (neighbors == null) { neighbors = grid.Get8Neighbors(cell); memoized[cell.C, cell.R] = neighbors; } foreach (GridCell n in neighbors) { if (expanded[n.C, n.R]) continue; if (grid.OccupiedCells[n.C, n.R] > 0) continue; if (grid.GVD.GetObstacleDistance(n) <= Car.HALF_CAR_WIDTH) continue; float dist = cell.C == n.C || cell.R == n.R ? 1f : sqrt2; dist += heuristic[cell.C, cell.R]; if (dist < heuristic[n.C, n.R]) { heuristic[n.C, n.R] = dist; open.Add(new GridCellValue(n, dist)); } } } }
public void IntervalHeap() { IntervalHeap<int> heap = new IntervalHeap<int>(Comparer<int>.Default); for (int i = 0; i < kHeapTestSize; ++i) heap.Insert(Random.Range(int.MinValue + 1, int.MaxValue)); Assert.IsTrue(heap.Validate()); int least = int.MinValue; int greatest = int.MaxValue; while (heap.Count > 0) { int next = heap.ExtractMin(); Assert.IsTrue(next >= least); least = next; next = heap.ExtractMax(); Assert.IsTrue(next <= greatest); greatest = next; } }
public ArrayList RunTSP(City[] Cities) { Route = new ArrayList(); Stopwatch timer = new Stopwatch(); bAndBTime = new TimeSpan(); timer.Start(); Greedy greedyAlgorithm = new Greedy(Cities); ArrayList greedyRoute = greedyAlgorithm.RunGreedyTSP(); double[,] matrix = new double[Cities.Length, Cities.Length]; //Populate each array item with each respective edge cost for (int i = 0; i < Cities.Length; i++) {//O(n^2) for (int j = 0; j < Cities.Length; j++) { if (i == j) { matrix[i, j] = double.PositiveInfinity; } else { matrix[i, j] = Cities[i].costToGetTo(Cities[j]); } } } IntervalHeap<State> queue = new IntervalHeap<State>(); double bestSolutionSoFar = greedyAlgorithm.BestSolutionSoFar(); bssfUpdatesAmt = 0; prunedAmt = 0; State bssfState = null; totalStatesCreated = 0; //Start with some problem State curState = new State(matrix, 0, new Edge(-1, -1)); totalStatesCreated++; //Reduce Matrix //O(4n^2) curState.Reduce(); //Let the queue be the set of active subproblems //O(log(n)) queue.Add(curState); maxQueueCount = 0; bool timesUp = false; while (queue.Count > 0) {//O(2^n) or O(2^(8n^2 + 9n + 2log(n))) if (timer.Elapsed.Seconds >= 30) { timesUp = true; break; } //Choose a subproblem and remove it from the queue if (queue.Count > maxQueueCount) { maxQueueCount = queue.Count; } //O(log(n)) curState = queue.DeleteMin(); if (curState.Cost() < bestSolutionSoFar) {//O(8n^2 + 9n + 2log(n)) //For each lowest cost (each 0) double highestScore = double.NegativeInfinity; State[] includeExcludeStates = new State[2]; foreach (Edge edge in curState.LowestNums()) {//O(8n^2 + 9n) //Include Matrix State includeState = new State(curState, edge); //O(n) totalStatesCreated++; includeState.IncludeMatrix(edge.Row(), edge.Col()); //O(4n^2 + 7n) //Exclude Matrix State excludeState = new State(curState, edge); //O(n) totalStatesCreated++; excludeState.ExcludeMatrix(edge.Row(), edge.Col());//O(4n^2) //Find the score for that edge (Exclude cost - Include cost) double score = excludeState.Cost() - includeState.Cost(); if (score > highestScore) { includeExcludeStates[0] = includeState; includeExcludeStates[1] = excludeState; highestScore = score; } } foreach (State subproblemState in includeExcludeStates) {//O(2log(n)) //if each P (subproblem) chosen is a complete solution, update the bssf if (subproblemState.CompleteSolution() && subproblemState.Cost() < bestSolutionSoFar) { bestSolutionSoFar = subproblemState.Cost(); bssfState = subproblemState; bssfUpdatesAmt++; } //else if lowerBound < bestSolutionSoFar else if (!subproblemState.CompleteSolution() && subproblemState.Cost() < bestSolutionSoFar) { //O(log(n)) queue.Add(subproblemState); } else { prunedAmt++; } } } } if (!timesUp) prunedAmt += queue.Count; //Call this the best solution so far. bssf is the route that will be drawn by the Draw method. if (bssfState != null) { int index = bssfState.Exited(0); Route.Add(Cities[index]); index = bssfState.Exited(bssfState.Exited(0)); while (index != bssfState.Exited(0)) {//O(n) Route.Add(Cities[index]); index = bssfState.Exited(index); } } else { Route = greedyRoute; } timer.Stop(); bAndBTime = timer.Elapsed; this.count = bssfState.Cost(); // update the cost of the tour. timer.Reset(); return Route; }
public void Dispose() { coll = null; rad16 = null; }
public void Init() { coll = new IntervalHeap<int>(); rad16 = new RadixFormatProvider(16); }
public void RemoveItemsFromHeap() { IntervalHeap<int> h = new IntervalHeap<int>(); for(int i = 0; i < 20; i++) { h.Push(i, i); } h.Remove(10); h.Remove(2); h.Remove(11); h.Remove(9); h.Remove(19); h.Remove(0); Assert.AreEqual(h.Pop(), 18); Assert.AreEqual(h.Pop(), 17); Assert.AreEqual(h.Pop(), 16); Assert.AreEqual(h.Pop(), 15); Assert.AreEqual(h.Pop(), 14); Assert.AreEqual(h.Pop(), 13); Assert.AreEqual(h.Pop(), 12); Assert.AreEqual(h.Pop(), 8); Assert.AreEqual(h.Pop(), 7); Assert.AreEqual(h.Pop(), 6); Assert.AreEqual(h.Pop(), 5); Assert.AreEqual(h.Pop(), 4); Assert.AreEqual(h.Pop(), 3); Assert.AreEqual(h.Pop(), 1); Assert.AreEqual(h.Count, 0); }
public void Replace5a() { for (int size = 0; size < 130; size++) { IPriorityQueue<double> q = new IntervalHeap<double>(); IPriorityQueueHandle<double> handle1 = null; q.Add(ref handle1, 3.0); Assert.AreEqual(3.0, q.FindMin()); for (int i = 1; i < size; i++) q.Add(i + 3.0); Assert.AreEqual(3.0, q.FindMin()); for (int min = 2; min >= -10; min--) { Assert.AreEqual(min + 1.0, q.Replace(handle1, min)); Assert.AreEqual(min, q.FindMin()); } Assert.AreEqual(-10.0, q.DeleteMin()); for (int i = 1; i < size; i++) Assert.AreEqual(i + 3.0, q.DeleteMin()); Assert.IsTrue(q.IsEmpty); } }
public void branchAndBoundSolve() { initialState = new State(new Double[Cities.Length, Cities.Length]); timer = new Stopwatch(); timer.Start(); for (int i = 0; i < Cities.Length; i++) //O(n^2), initialize initialStates map { for (int x = 0; x < Cities.Length; x++) { initialState.setPoint(i, x, Cities[i].costToGetTo(Cities[x])); if (initialState.getPoint(i, x) == 0) initialState.setPoint(i, x, double.PositiveInfinity); } } initialState.initializeEdges(); //initializeEdges initializes the state's dictionary //with key 0 to n (# of cities), value -> -1 reduceMatrix(initialState); //reduce the matrix to find lower bound queue = new IntervalHeap<State>(); //this is a global queue BSSF = greedy(); //find initial best solution so far, O(n^4) Console.WriteLine("BSSF: " + BSSF); findGreatestDiff(initialState); //exclude minus include, O(n^3) TimeSpan ts = timer.Elapsed; bool terminatedEarly = false; //boolean to keep track if we stopped after 30 seconds int maxStates = 0; //keeps track of the maximum amount of states in the queue at one point int totalSeconds = 0; while (queue.Count != 0) //O(2^n * n^3), because each time you expand a node, it expands it 2 times, exponentially { //where n is the number of cities if (queue.Count > maxStates) //if maxStates needs to be updated, update it maxStates = queue.Count; ts = timer.Elapsed; State min = queue.DeleteMin(); if (totalSeconds < ts.Seconds) { totalSeconds = ts.Seconds; Console.WriteLine("seconds: " + totalSeconds); } if (min.getLB() < BSSF) //if the min popped off the queue has a lowerbound less than findGreatestDiff(min);//the BSSF, expand it, otherwise, prune it. -> O(n^3) else {//all of the lowerbounds are worse than the BSSF, break! break; } } if (!terminatedEarly)//if it solved the problem in less than 30 seconds { int city = 0; for (int i = 0; i < bestState.getEdges().Count; i++) //O(n) { if (i == 0) //outputting a map into the Route list { Route.Add(Cities[i]); city = bestState.getEdge(i); } else { Route.Add(Cities[city]); city = bestState.getEdge(city); } } bssf = new TSPSolution(Route); // update the cost of the tour. Program.MainForm.tbCostOfTour.Text = " " + bssf.costOfRoute(); Program.MainForm.tbElapsedTime.Text = ts.TotalSeconds.ToString(); // do a refresh. Program.MainForm.Invalidate(); } }
public void Bug20130208() { IPriorityQueue<double> q = new IntervalHeap<double>(); IPriorityQueueHandle<double> h0 = null, h2 = null, h4 = null, h7 = null, h5 = null; // Add(43, 0); q.Add(ref h0, 43); // Remove(); q.DeleteMin(); // XAddMaxReplace(9, 2); q.Add(ref h2, Double.MaxValue); q[h2] = 9; // XAddMaxReplace(32, 4); q.Add(ref h4, Double.MaxValue); q[h4] = 32; // XAddMaxReplace(44, 7); q.Add(ref h7, Double.MaxValue); q[h7] = 44; // Remove(); q.DeleteMin(); // XAddMaxReplace(0, 5); q.Add(ref h5, Double.MaxValue); q[h5] = 0; // Internally inconsistent data structure already now Assert.IsTrue(q.Check()); }
public void Bug20130208Case3() { // Case 3: only left.first IPriorityQueue<double> q = new IntervalHeap<double>(); IPriorityQueueHandle<double> topRight = null; q.Add(20); q.Add(ref topRight, 30); q.Add(25); q[topRight] = 10; Assert.IsTrue(q.Check()); Assert.IsTrue(q.FindMax() == 25); }
/// <summary> /// Creates a new IPriorityQueue containing submitted /// Node elements. /// </summary> /// <param name="nodes">Elements to create queue with.</param> /// <param name="goal">The goal node</param> /// <returns>A IPriorityQueue containing sumbitted nodes.</returns> private IPriorityQueue<PriorityQueueNode> CreateQueue(Node[][] nodes, Node goal) { IntervalHeap<PriorityQueueNode> queue = new IntervalHeap<PriorityQueueNode>(PriorityQueueNode.SortByDirectedDistance(goal)); foreach (Node[] subnodes in nodes) foreach (PriorityQueueNode node in subnodes) { node.Handle = null; } return queue; }
public void Replace5b() { for (int size = 0; size < 130; size++) { IPriorityQueue<double> q = new IntervalHeap<double>(); IPriorityQueueHandle<double> handle1 = null; q.Add(ref handle1, -3.0); Assert.AreEqual(-3.0, q.FindMax()); for (int i = 1; i < size; i++) q.Add(-i - 3.0); Assert.AreEqual(-3.0, q.FindMax()); for (int max = -2; max <= 10; max++) { Assert.AreEqual(max - 1.0, q.Replace(handle1, max)); Assert.AreEqual(max, q.FindMax()); } Assert.AreEqual(10.0, q.DeleteMax()); for (int i = 1; i < size; i++) Assert.AreEqual(-i - 3.0, q.DeleteMax()); Assert.IsTrue(q.IsEmpty); } }
/// <summary>Write item predictions (scores) to a TextWriter object</summary> /// <param name="recommender">the <see cref="IRecommender"/> to use for making the predictions</param> /// <param name="user_id">ID of the user to make recommendations for</param> /// <param name="candidate_items">list of candidate items</param> /// <param name="ignore_items">list of items for which no predictions should be made</param> /// <param name="num_predictions">the number of items to return per user, -1 if there should be no limit</param> /// <param name="writer">the <see cref="TextWriter"/> to write to</param> /// <param name="user_mapping">an <see cref="IEntityMapping"/> object for the user IDs</param> /// <param name="item_mapping">an <see cref="IEntityMapping"/> object for the item IDs</param> public static void WritePredictions( this IRecommender recommender, int user_id, System.Collections.Generic.IList<int> candidate_items, System.Collections.Generic.ICollection<int> ignore_items, int num_predictions, TextWriter writer, IEntityMapping user_mapping, IEntityMapping item_mapping) { System.Collections.Generic.IList<Pair<int, float>> ordered_items; if (user_mapping == null) user_mapping = new IdentityMapping(); if (item_mapping == null) item_mapping = new IdentityMapping(); if (num_predictions == -1) { var scored_items = new List<Pair<int, float>>(); foreach (int item_id in candidate_items) if (!ignore_items.Contains(item_id)) { float score = recommender.Predict(user_id, item_id); if (score > float.MinValue) scored_items.Add(new Pair<int, float>(item_id, score)); } ordered_items = scored_items.OrderByDescending(x => x.Second).ToArray(); } else { var comparer = new DelegateComparer<Pair<int, float>>( (a, b) => a.Second.CompareTo(b.Second) ); var heap = new IntervalHeap<Pair<int, float>>(num_predictions, comparer); float min_relevant_score = float.MinValue; foreach (int item_id in candidate_items) if (!ignore_items.Contains(item_id)) { float score = recommender.Predict(user_id, item_id); if (score > min_relevant_score) { heap.Add(new Pair<int, float>(item_id, score)); if (heap.Count > num_predictions) { heap.DeleteMin(); min_relevant_score = heap.FindMin().Second; } } } ordered_items = new Pair<int, float>[heap.Count]; for (int i = 0; i < ordered_items.Count; i++) ordered_items[i] = heap.DeleteMax(); } writer.Write("{0}\t[", user_mapping.ToOriginalID(user_id)); if (ordered_items.Count > 0) { writer.Write("{0}:{1}", item_mapping.ToOriginalID(ordered_items[0].First), ordered_items[0].Second.ToString(CultureInfo.InvariantCulture)); for (int i = 1; i < ordered_items.Count; i++) { int item_id = ordered_items[i].First; float score = ordered_items[i].Second; writer.Write(",{0}:{1}", item_mapping.ToOriginalID(item_id), score.ToString(CultureInfo.InvariantCulture)); } } writer.WriteLine("]"); }
void ResetSearchNodes() { //OpenList.Clear(); //ClosedList.Clear(); //OpenList = new List<PathNode>(); OpenList = new IntervalHeap<PathNode>(nodeComparer); //ClosedList = new List<PathNode>(); CleanupList = new List<PathNode>(); /*foreach (PathNode node in PathNodes) { if (node != null) { node.InOpenList = false; node.InClosedList = false; //node.DistanceTravelled = float.MaxValue; //node.DistanceToGoal = float.MaxValue; } }*/ /*for (int y = 0; y < Map.Height; y++) { for (int x = 0; x < Map.Width; x++) { PathNode node = PathNodes[y, x]; if (node == null) continue; node.InOpenList = false; node.InClosedList = false; node.DistanceTravelled = float.MaxValue; node.DistanceToGoal = float.MaxValue; } }*/ }
public List<Cell> FindPath(Point start, Point end) { m_open = new IntervalHeap<Cell>(m_capacity, new CellComparer()); m_closed = new List<Cell>(m_capacity); Cell temp; // Set parent to a starting point and set its g, h, f values Cell parent = this[start.X, start.Y]; parent.G = 0; parent.H = EstimateCost(start, end); parent.F = parent.G + parent.H; // Add parent to the open list, should be the only cell at this point m_open.Add(parent); while ( ! m_open.IsEmpty) { // Find the cell with the lowest f value // Pop it off the open and assign the value to parent parent = m_open.DeleteMin(); // If the best cell is the end, we're done if (parent.Coord == end) { m_closed.Add(parent); return ReconstructReversePath(m_closed); } // Walk through valid adjacent cells foreach (Point p in parent.Adjacent) { if (p.X >= 0 && p.Y >= 0 && p.X < m_width && p.Y < m_height) { int g = parent.G + GetCellCost(this[p]); if (g == parent.G) continue; // Check if m_open or m_closed contain a Cell with lower G value if (m_open.Find(n => n.Equals(this[p]), out temp) && temp.G <= g) continue; if (m_closed.Contains(this[p]) && m_closed.Find(n => n.Equals(this[p])).G <= g) continue; this[p].Parent = parent; this[p].G = g; this[p].H = EstimateCost(this[p].Coord, end); this[p].F = this[p].G + this[p].H; m_open.Add(this[p]); } } m_closed.Add(parent); } return null; }
public void Bug20130208Case6b() { // Case 6b: both right.first and right.last, not max IPriorityQueue<double> q = new IntervalHeap<double>(); IPriorityQueueHandle<double> topRight = null; q.Add(20); q.Add(ref topRight, 30); q.Add(24); q.Add(28); q.Add(23); q.Add(26); q[topRight] = 10; Assert.IsTrue(q.Check()); Assert.IsTrue(q.FindMax() == 28); }