Count() 공개 메소드

public Count ( ) : int
리턴 int
예제 #1
0
        private static void WriteToPosition(ISaItemTsvWriter writer, MinHeap <SupplementaryDataItem> itemsHeap, int position)
        {
            if (itemsHeap.Count() == 0)
            {
                return;
            }
            var bufferMin = itemsHeap.GetMin();

            while (bufferMin.Start < position)
            {
                var itemsAtMinPosition = new List <SupplementaryDataItem>();

                while (itemsHeap.Count() > 0 && bufferMin.CompareTo(itemsHeap.GetMin()) == 0)
                {
                    itemsAtMinPosition.Add(itemsHeap.ExtractMin());
                }

                writer.WritePosition(itemsAtMinPosition);

                if (itemsHeap.Count() == 0)
                {
                    break;
                }

                bufferMin = itemsHeap.GetMin();
            }
        }
예제 #2
0
        private void WriteUptoPosition(MinHeap <ISupplementaryDataItem> itemsHeap, int position)
        {
            if (position < 1)
            {
                return;
            }
            if (itemsHeap.Count() == 0)
            {
                return;
            }
            var bufferMin = itemsHeap.GetMin();

            while (bufferMin.Position < position)
            {
                var itemsAtMinPosition = new List <ISupplementaryDataItem>();

                while (itemsHeap.Count() > 0 && SuppDataUtilities.CompareTo(bufferMin, itemsHeap.GetMin()) == 0)
                {
                    itemsAtMinPosition.Add(itemsHeap.ExtractMin());
                }

                if (itemsAtMinPosition.Count > 0)
                {
                    _count += itemsAtMinPosition.Count;
                    WritePosition(itemsAtMinPosition);
                }
                if (itemsHeap.Count() == 0)
                {
                    break;
                }

                bufferMin = itemsHeap.GetMin();
            }
        }
예제 #3
0
        /// <summary>
        /// Find median of 2 sorted arrays balancing heaps
        /// </summary>
        /// <param name="nums"></param>
        /// <returns></returns>
        public static double FindMedianSortedArrays(int[] nums1, int[] nums2)
        {
            var minHeap = new MinHeap <int>();
            var maxHeap = new MaxHeap <int>();

            // An integer from the array is first added to the minheap.
            int i = 0, j = 0;

            for (; i < nums1.Length && j < nums2.Length;)
            {
                int nextNum;
                if (nums1[i] > nums2[j])
                {
                    nextNum = nums2[j];
                    j++;
                }
                else
                {
                    nextNum = nums1[i];
                    i++;
                }

                BalanceHeaps(minHeap, maxHeap, nextNum);
            }

            while (i < nums1.Length)
            {
                BalanceHeaps(minHeap, maxHeap, nums1[i]);
                i++;
            }

            while (j < nums2.Length)
            {
                BalanceHeaps(minHeap, maxHeap, nums2[j]);
                j++;
            }

            // In the end, the median is found by using the peek element from min-heap and peek element from the max-heap
            double median;

            if (minHeap.Count() == maxHeap.Count())
            {
                median = (minHeap.Peek() + maxHeap.Peek()) / 2.0;
            }
            else if (minHeap.Count() > maxHeap.Count())
            {
                median = minHeap.Peek();
            }
            else
            {
                median = maxHeap.Peek();
            }

            return(median);
        }
예제 #4
0
        //SOLUTION FOR LEETCODE QUESTION:
        //253 - MEETING ROOMS II - Given an array of meeting time intervals intervals where intervals[i] = [starti, endi],
        //return the minimum number of conference rooms required.
        //*****DIFFICULTY - MEDIUM*****


        /// <summary>
        /// Method the returns minimum number of meeting rooms needed given an array of meeting intervals
        /// </summary>
        /// <param name="intervals"></param>
        /// <returns>Number of meeting rooms</returns>
        public int MinMeetingRooms(int[][] intervals)
        {
            //Sort intervals by starting time
            Array.Sort(intervals, (item1, item2) => { return(item1[0].CompareTo(item2[0])); });

            //Invoking MiniHeap class
            var minHeap = new MinHeap(intervals.Length);

            //Add the end time of the first interval to the MinHeap
            minHeap.Add(intervals[0][1]);

            //For each other interval, check if the start time is less than the current min on heap
            for (int i = 1; i < intervals.Length; i++)
            {
                //If true add the end of current interval to MinHeap
                if (intervals[i][0] >= minHeap.Peek())
                {
                    minHeap.Pop();
                }

                //If false, pop the min and add the current end time to heap
                minHeap.Add(intervals[i][1]);
            }

            //The number of elements left in the MinHeap will tell us the number of rooms needed
            return(minHeap.Count());
        }
예제 #5
0
        /*
         *  Meeting Rooms II
         *  Given an array of meeting time intervals consisting of start and
         *  end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum
         *  number of conference rooms required.
         *
         *  Example 1:
         *
         *  Input: [[0, 30],[5, 10],[15, 20]]
         *  Output: 2
         */

        public static int MinMeetingRooms(int[][] intervals)
        {
            // TC (1, 10), (2, 7), (3, 19), (8, 12), (10, 20), (11, 30)

            // If there is no meeting to schedule then no room needs to be allocated.
            if (intervals == null || !intervals.Any())
            {
                return(0);
            }

            // Sort the meetings in increasing order of their start time.
            Array.Sort(intervals, new StartTimeComparer());

            var availableRoomsHeap = new MinHeap <int>();

            // Add the first meeting. We have to give a new room to the first meeting.
            availableRoomsHeap.Push(intervals[0][1]);

            for (var i = 1; i < intervals.Length; i++)
            {
                // If the room due to free up the earliest is free, assign that room to this meeting.
                if (availableRoomsHeap.Peek() <= intervals[i][0])
                {
                    availableRoomsHeap.Pop();
                }

                // If a new room is to be assigned, then also we add to the heap,
                // If an old room is allocated, then also we have to add to the heap with updated end time.
                availableRoomsHeap.Push(intervals[i][1]);
            }

            // The size of the heap tells us the minimum rooms required for all the meetings.
            return(availableRoomsHeap.Count());
        }
예제 #6
0
        public void Displace01()
        {
            var minheap = new MinHeap<int>(2);
            Assert.AreEqual(0, minheap.Count());
            minheap.Insert(5);
            minheap.Insert(4);
            Assert.AreEqual(4, minheap.Displace(6));
            Assert.AreEqual(2, minheap.Count());
            Assert.AreEqual(5, minheap.Peek());

            var maxheap = new MaxHeap<int>(2);
            Assert.AreEqual(0, maxheap.Count());
            maxheap.Insert(3);
            maxheap.Insert(4);
            Assert.AreEqual(4, maxheap.Displace(2));
            Assert.AreEqual(2, maxheap.Count());
            Assert.AreEqual(3, maxheap.Peek());
        }
예제 #7
0
        public void Delete01()
        {
            var minheap = new MinHeap<int>(2);
            Assert.AreEqual(0, minheap.Count());
            minheap.Insert(1);
            minheap.Insert(0);
            Assert.Throws<InvalidOperationException>(() => { minheap.Insert(-1); });
            Assert.AreEqual(0, minheap.Delete());
            Assert.AreEqual(1, minheap.Count());

            var maxheap = new MaxHeap<int>(2);
            Assert.AreEqual(0, maxheap.Count());
            maxheap.Insert(0);
            maxheap.Insert(1);
            Assert.Throws<InvalidOperationException>(() => { maxheap.Insert(-1); });
            Assert.AreEqual(1, maxheap.Delete());
            Assert.AreEqual(1, maxheap.Count());
        }
예제 #8
0
        private static (Dictionary <(string refAllele, string altAllele), GnomadItem> genomeItems, Dictionary <(string refAllele, string altAllele), GnomadItem> exomeItems) GetMinItems(MinHeap <GnomadItem> minHeap)
        {
            var genomeItems = new List <ISupplementaryDataItem>();
            var exomeItems  = new List <ISupplementaryDataItem>();

            if (minHeap.Count() == 0)
            {
                return(null, null);
            }
            var position = minHeap.GetMin().Position;

            while (minHeap.Count() > 0 && minHeap.GetMin().Position == position)
            {
                var item = minHeap.ExtractMin();
                if (item.DataType == GnomadDataType.Genome)
                {
                    genomeItems.Add(item);
                }
                else
                {
                    exomeItems.Add(item);
                }
            }

            genomeItems = SuppDataUtilities.RemoveConflictingAlleles(genomeItems, false);
            exomeItems  = SuppDataUtilities.RemoveConflictingAlleles(exomeItems, false);

            var genomeItemsByAllele = new Dictionary <(string refAllele, string altAllele), GnomadItem>();

            foreach (var item in genomeItems)
            {
                genomeItemsByAllele.Add((item.RefAllele, item.AltAllele), (GnomadItem)item);
            }

            var exomeItemsByAllele = new Dictionary <(string refAllele, string altAllele), GnomadItem>();

            foreach (var item in exomeItems)
            {
                exomeItemsByAllele.Add((item.RefAllele, item.AltAllele), (GnomadItem)item);
            }
            return(genomeItemsByAllele, exomeItemsByAllele);
        }
예제 #9
0
        public void Delete01()
        {
            var minheap = new MinHeap <int>(2);

            Assert.AreEqual(0, minheap.Count());
            minheap.Insert(1);
            minheap.Insert(0);
            Assert.Throws <InvalidOperationException>(() => { minheap.Insert(-1); });
            Assert.AreEqual(0, minheap.Delete());
            Assert.AreEqual(1, minheap.Count());

            var maxheap = new MaxHeap <int>(2);

            Assert.AreEqual(0, maxheap.Count());
            maxheap.Insert(0);
            maxheap.Insert(1);
            Assert.Throws <InvalidOperationException>(() => { maxheap.Insert(-1); });
            Assert.AreEqual(1, maxheap.Delete());
            Assert.AreEqual(1, maxheap.Count());
        }
예제 #10
0
        public void Displace01()
        {
            var minheap = new MinHeap <int>(2);

            Assert.AreEqual(0, minheap.Count());
            minheap.Insert(5);
            minheap.Insert(4);
            Assert.AreEqual(4, minheap.Displace(6));
            Assert.AreEqual(2, minheap.Count());
            Assert.AreEqual(5, minheap.Peek());

            var maxheap = new MaxHeap <int>(2);

            Assert.AreEqual(0, maxheap.Count());
            maxheap.Insert(3);
            maxheap.Insert(4);
            Assert.AreEqual(4, maxheap.Displace(2));
            Assert.AreEqual(2, maxheap.Count());
            Assert.AreEqual(3, maxheap.Peek());
        }
예제 #11
0
        public void AddAndCount()
        {
            // Arrange
            var minHeap = new MinHeap <int>();

            // Act & Assert
            for (var i = 0; i < 1000000; i++)
            {
                minHeap.Add(i);
                Assert.AreEqual(i + 1, minHeap.Count());
            }
        }
예제 #12
0
        public void Insert02()
        {
            var minheap = new MinHeap <int>(3);

            Assert.AreEqual(0, minheap.Count());
            minheap.Insert(0);
            Assert.AreEqual(1, minheap.Count());
            minheap.Insert(0);
            Assert.AreEqual(2, minheap.Count());
            minheap.Insert(2);
            Assert.AreEqual(3, minheap.Count());

            var maxheap = new MaxHeap <int>(3);

            Assert.AreEqual(0, maxheap.Count());
            maxheap.Insert(0);
            Assert.AreEqual(1, maxheap.Count());
            maxheap.Insert(0);
            Assert.AreEqual(2, maxheap.Count());
            maxheap.Insert(1);
            Assert.AreEqual(3, maxheap.Count());
        }
예제 #13
0
        private static void BalanceHeaps(MinHeap <int> minHeap, MaxHeap <int> maxHeap, int nextNum)
        {
            // An integer from the file is first added to the min-heap.
            // Then while the max-heap peek element is smaller than the min-heap peek element, insert max-heap elements into min-heap.
            minHeap.Push(nextNum);
            while (maxHeap.Any() && maxHeap.Peek() < minHeap.Peek())
            {
                minHeap.Push(maxHeap.Pop());
            }

            // Now we adjust the heap by repeatedly moving min-heap peek element into the max-heap until their size difference is at the max 1 element.
            // Now adjust their sizes to |min size - max size| == 1
            while (System.Math.Abs(minHeap.Count() - maxHeap.Count()) > 1)
            {
                maxHeap.Push(minHeap.Pop());
            }
        }
예제 #14
0
        public void Dequeue()
        {
            MinHeap <int> heap       = new MinHeap <int>();
            int           targetItem = 1;
            int           targetSize = 2;

            heap.Enqueue(10);
            heap.Enqueue(5);
            heap.Enqueue(targetItem);


            int actualItem = heap.Dequeue();
            int actualSize = heap.Count();

            Assert.AreEqual(actualItem, targetItem);
            Assert.AreEqual(actualSize, targetSize);
        }
예제 #15
0
            public void AddNum(int num)
            {
                // Add to max heap
                _lowerHalf.Push(num);

                // Balancing the Tree
                _higherHalf.Push(_lowerHalf.Peek());
                _lowerHalf.Pop();

                if (_lowerHalf.Count() < _higherHalf.Count())
                {
                    // Maintain the size property
                    _lowerHalf.Push(_higherHalf.Peek());
                    _higherHalf.Pop();
                }

                _count++;
            }
예제 #16
0
        public void AddSameAndPop()
        {
            // Arrange
            var minHeap = new MinHeap <int>();

            // Act
            minHeap.Add(0);
            minHeap.Add(0);
            minHeap.Add(0);
            minHeap.Add(0);
            minHeap.Add(0);

            // Assert
            Assert.AreEqual(5, minHeap.Count());
            Assert.AreEqual(0, minHeap.Pop());
            Assert.AreEqual(0, minHeap.Pop());
            Assert.AreEqual(0, minHeap.Pop());
            Assert.AreEqual(0, minHeap.Pop());
            Assert.AreEqual(0, minHeap.Pop());
        }
예제 #17
0
        public void Insert02()
        {
            var minheap = new MinHeap<int>(3);
            Assert.AreEqual(0, minheap.Count());
            minheap.Insert(0);
            Assert.AreEqual(1, minheap.Count());
            minheap.Insert(0);
            Assert.AreEqual(2, minheap.Count());
            minheap.Insert(2);
            Assert.AreEqual(3, minheap.Count());

            var maxheap = new MaxHeap<int>(3);
            Assert.AreEqual(0, maxheap.Count());
            maxheap.Insert(0);
            Assert.AreEqual(1, maxheap.Count());
            maxheap.Insert(0);
            Assert.AreEqual(2, maxheap.Count());
            maxheap.Insert(1);
            Assert.AreEqual(3, maxheap.Count());
        }
        /// <summary>
        /// try to use MinHeap - August 15, 2018
        /// Requirement:
        /// 1. Remove third maximum number;
        /// 2. If total of distinct numbers is less than three, remove maximum number.
        /// Tips:
        /// 1. Design a minimum heap using C# SortedSet;
        /// 2. If there is less than three distinct numbers in the array, return maximum one;
        /// 3. Always keep minimum heap size on check, make sure that it is less and equal to 3;
        /// 4. More on step 3, if the size of heap is bigger than three, remove minimum one;
        /// 5. Go over all the numbers in the array, put them to heap;
        /// 6. Remove smallest one at the end.
        /// </summary>
        /// <param name="numbers"></param>
        /// <returns></returns>
        public static int ThirdMax(int[] numbers)
        {
            if (numbers == null || numbers.Length == 0)
            {
                return(-1);
            }

            int size        = 0;
            var length      = numbers.Length;
            var minimumHeap = new MinHeap();
            var count       = 0;

            for (int i = 0; i < length && size < 3; i++)
            {
                minimumHeap.Add(numbers[i]);
                size = minimumHeap.Count(); // caught by online judge, heap excludes duplicate
                count++;
            }

            // if the array has less than three distinct number, return maximum one
            if (count == length && size < 3)
            {
                return(minimumHeap.GetLast());
            }

            for (int i = count; i < length; i++)
            {
                var current = numbers[i];

                // if the current number is in the minimm heap or smaller than minimum value in the heap
                if (minimumHeap.Contains(current) || current < minimumHeap.GetMin())
                {
                    continue;
                }

                minimumHeap.RemoveMin();
                minimumHeap.Add(current);
            }

            return(minimumHeap.GetMin());
        }
예제 #19
0
        // Adds a num into the data structure.
        public void AddNum(double num)
        {
            if (upperPortion.Count() == lowerPortion.Count())
            {
                // Insert the new element where it belongs
                if (upperPortion.Count() > 0 && num > upperPortion.peekMin())
                {
                    upperPortion.Add(num);
                    lowerPortion.Add(upperPortion.removeMin()); // Rebalance the heaps so that lowerPortion has N/2 + 1 elements
                }
                else
                {
                    lowerPortion.Add(num);
                }
            }

            else // after the insertion we'll have an even number of elements
            {
                if (upperPortion.Count() > 0 && num > upperPortion.peekMin())
                {
                    upperPortion.Add(num);
                    if (upperPortion.Count() > lowerPortion.Count())
                    {
                        lowerPortion.Add(upperPortion.removeMin());
                    }
                }
                else
                {
                    lowerPortion.Add(num);
                    if (lowerPortion.Count() > upperPortion.Count())
                    {
                        upperPortion.Add(lowerPortion.removeMax());
                    }
                }
            }
        }
예제 #20
0
 public int Count()
 {
     return(minHeap.Count());
 }
예제 #21
0
    public List <Node> FindPath(Vector3 startposition, Vector3 goalposition, int algorithmindex, int heuristicindex, out string unitmessage)
    {
        ResetNodeParentgCostAndhCost();
        ClearLists();

        Node startNode = grid.GetNodeFromWorldPoint(startposition);
        Node goalNode  = grid.GetNodeFromWorldPoint(goalposition);
        Node currentNode;

        Stopwatch timer = new Stopwatch();

        int    nodesExploredCount = 0;
        string pathfindingUsed    = "";

        startNode.gCost = 0;
        startNode.hCost = grid.GetNodeDistance(startNode, goalNode, heuristicindex) + (int)startNode.nodeType;
        openList.Add(startNode);
        timer.Start();

        while (openList.Count() > 0)
        {
            currentNode = openList.RemoveFrontItem();

            if (!closedList.Contains(currentNode))
            {
                closedList.Add(currentNode);
                nodesExploredCount++;
            }

            switch (algorithmindex)
            {
            case 0:
                ExpandDijkstraOpenList(currentNode, heuristicindex);
                pathfindingUsed = "Dijkstra with ";
                break;

            case 1:
                ExpandBestFirstSearchOpenList(currentNode, goalNode, heuristicindex);
                pathfindingUsed = "Greedy Best First Search with ";
                break;

            case 2:
                ExpandAStarOpenList(currentNode, goalNode, heuristicindex);
                pathfindingUsed = "A* Pathfinding with ";
                break;

            default:
                break;
            }

            if (openList.Contains(goalNode))
            {
                pathList = GetPathNodes(goalNode);
                timer.Stop();
                unitmessage = ((pathfindingUsed)
                               + (HeuristicUsed(heuristicindex))
                               + ("Elapsed time = ")
                               + (timer.Elapsed.TotalMilliseconds).ToString()
                               + " milliseconds , Nodes Explored = "
                               + nodesExploredCount.ToString()
                               + ", Nodes To Goal = "
                               + pathList.Count.ToString());


                return(pathList);
            }
        }
        unitmessage = ("Path is blocked, no path possible to goal");
        return(null);
    }
    private void Astar()
    {
        start.isInOpenSetOfThread[id] = true;
        MinHeap openSet = new MinHeap(start, id);

        openSet.Add(start);


        start.gScores[id] = 0;
        start.fScores[id] = start.gScores[id] + Heuristic_cost_estimate(goal, start);

        int numSteps = 0;

        while (!finished)
        {
            Node current = openSet.GetRoot();
            current.isInOpenSetOfThread[id] = false;
            current.isInClosedSet           = true;

            current.isCurrent = true;
            ControlLogic(current, numSteps);
            numSteps++;
            current.isCurrent = false;

            if (current.checkedByThread == 0)
            {
                if (current.fScores[id] < (int)L && current.gScores[id] + brotherThread.F - brotherThread.Heuristic_cost_estimate(start, current) < (int)L)
                {
                    foreach (Node neighbor in current.getNeighbors())
                    {
                        if (neighbor != null && neighbor.isWalkable)
                        {
                            int cost = Heuristic_cost_estimate(current, neighbor);
                            if (neighbor.checkedByThread == 0 && neighbor.gScores[id] > current.gScores[id] + cost)
                            {
                                neighbor.gScores[id] = current.gScores[id] + cost;
                                neighbor.fScores[id] = neighbor.gScores[id] + Heuristic_cost_estimate(goal, neighbor);
                                neighbor.parents[id] = current;
                                if (!neighbor.isInOpenSetOfThread[id])
                                {
                                    neighbor.isInOpenSetOfThread[id] = true;
                                    openSet.Add(neighbor);
                                }
                                else
                                {
                                    openSet.Reevaluate(neighbor);
                                }
                                if (neighbor.gScores[brotherThread.id] != int.MaxValue && neighbor.gScores[brotherThread.id] + neighbor.gScores[id] < (int)L)
                                {
                                    lock (L)
                                    {
                                        if (neighbor.gScores[brotherThread.id] + neighbor.gScores[id] < (int)L)
                                        {
                                            L       = neighbor.gScores[brotherThread.id] + neighbor.gScores[id];
                                            endNode = current;
                                            brotherThread.endNode = neighbor;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                current.checkedByThread = id;
            }

            if (openSet.Count() > 0)
            {
                F = openSet.Peek().fScores[id];
            }
            else
            {
                finished = true;
            }
        }
    }
예제 #23
0
    public List<Node> Astar(Node start, Node goal)
    {
        if (start == null || goal == null){
            return null;
        }

        if (start == goal)
        {
            return new List<Node> {start};
        }

        foreach(Node node in objectManager.NodeManager.nodes)
        {
            node.Reset();
        }

        MinHeap openSet = new MinHeap(start);
        start.IsInOpenSet = true;

        start.gScore = 0;
        start.fScore = start.gScore + Heuristic_cost_estimate (goal, start);

        Node current = null;
        while (openSet.Count() > 0) {

            current = openSet.GetRoot ();

            current.IsInOpenSet = false;
            current.IsInClosedSet = true;

            if (current == goal)
            {
                return Reconstruct_path (start, goal);
            }

            foreach (Node neighbor in current.BorderTiles) {
                if(neighbor == null || !neighbor.IsWalkable || neighbor.IsInClosedSet)
                    continue;

                // if the new gscore is lower replace it
                int tentativeGscore = current.gScore + Heuristic_cost_estimate (current, neighbor);

                if (!neighbor.IsInOpenSet || tentativeGscore < neighbor.gScore) {

                    neighbor.parent = current;
                    neighbor.gScore = tentativeGscore;
                    neighbor.fScore = neighbor.gScore + Heuristic_cost_estimate (goal, neighbor);

                    if (!neighbor.IsInOpenSet){
                        openSet.Add (neighbor);
                        neighbor.IsInOpenSet = true;
                    }
                    else
                    {
                        openSet.Reevaluate(neighbor);
                    }
                }
            }
        }
        // Fail
        return null;
    }
예제 #24
0
        /// <summary>
        /// Merging genomic an exomic items to create one stream of gnomad entries
        /// </summary>
        /// <returns></returns>
        public IEnumerable <GnomadItem> GetCombinedItems()
        {
            using (var genomeEnumerator = GetItems(_genomeReader, GnomadDataType.Genome).GetEnumerator())
                using (var exomeEnumerator = GetItems(_exomeReader, GnomadDataType.Exome).GetEnumerator())
                {
                    var hasGenomicItem = genomeEnumerator.MoveNext();
                    var hasExomeItem   = exomeEnumerator.MoveNext();

                    var minHeap = new MinHeap <GnomadItem>(GnomadItem.CompareTo);
                    while (hasExomeItem && hasGenomicItem)
                    {
                        var genomeItem = genomeEnumerator.Current;
                        var exomeItem  = exomeEnumerator.Current;
                        var position   = Math.Min(genomeItem.Position, exomeItem.Position);

                        while (hasGenomicItem && genomeItem.Position == position)
                        {
                            //all items for a position should be gathered so as to resolve conflicts properly
                            minHeap.Add(GnomadUtilities.GetNormalizedItem(genomeItem, _sequenceProvider));
                            hasGenomicItem = genomeEnumerator.MoveNext();
                            genomeItem     = genomeEnumerator.Current;
                        }

                        while (hasExomeItem && exomeItem.Position == position)
                        {
                            minHeap.Add(GnomadUtilities.GetNormalizedItem(exomeItem, _sequenceProvider));
                            hasExomeItem = exomeEnumerator.MoveNext();
                            exomeItem    = exomeEnumerator.Current;
                        }
                        // at this point, the min heap should not be empty
                        int heapPosition = minHeap.GetMin().Position;

                        while (minHeap.Count() > 0 && heapPosition < position - VariantUtils.MaxUpstreamLength)
                        {
                            var(genomeItems, exomeItems) = GetMinItems(minHeap);
                            foreach (var item in GnomadUtilities.GetMergedItems(genomeItems, exomeItems).Values)
                            {
                                if (item.AllAlleleNumber == null || item.AllAlleleNumber.Value == 0)
                                {
                                    continue;
                                }
                                yield return(item);
                            }
                        }
                    }
                    //flush out the last positions in heap
                    while (minHeap.Count() > 0)
                    {
                        var(genomeItems, exomeItems) = GetMinItems(minHeap);
                        foreach (var item in GnomadUtilities.GetMergedItems(genomeItems, exomeItems).Values)
                        {
                            yield return(item);
                        }
                    }
                    //now, only one of the iterator is left
                    if (hasGenomicItem)
                    {
                        foreach (var item in GetRemainingItems(genomeEnumerator))
                        {
                            yield return(item);
                        }
                    }

                    if (hasExomeItem)
                    {
                        foreach (var item in GetRemainingItems(exomeEnumerator))
                        {
                            yield return(item);
                        }
                    }
                }
        }
    public void Astar()
    {
        if (start == null || goal == null)
        {
            done = true;
            return;
        }

        if (start == goal)
        {
            done = true;
            return;
        }

        MinHeap openSet = new MinHeap(start);

        start.isInOpenSet = true;

        start.gScore = 0;
        start.fScore = start.gScore + Heuristic_cost_estimate(goal, start);

        int  numSteps = 0;
        Node current  = null;

        while (openSet.Count() > 0)
        {
            current = openSet.GetRoot();

            current.isCurrent     = true;
            current.isInOpenSet   = false;
            current.isInClosedSet = true;

            ControlLogic(current, numSteps);
            numSteps++;
            current.isCurrent = false;


            if (current == goal)
            {
                pathToDestination = Reconstruct_path(start, goal);
                done = true;
                return;
            }

            foreach (Node neighbor in current.getNeighbors())
            {
                if (neighbor == null || !neighbor.isWalkable || neighbor.isInClosedSet)
                {
                    continue;
                }

                // if the new gscore is lower replace it
                int tentativeGscore = current.gScore + Heuristic_cost_estimate(current, neighbor);

                if (!neighbor.isInOpenSet || tentativeGscore < neighbor.gScore)
                {
                    neighbor.parent = current;
                    neighbor.gScore = tentativeGscore;
                    neighbor.fScore = neighbor.gScore + Heuristic_cost_estimate(goal, neighbor);

                    if (!neighbor.isInOpenSet)
                    {
                        openSet.Add(neighbor);
                        neighbor.isInOpenSet = true;
                    }
                    else
                    {
                        openSet.Reevaluate(neighbor);
                    }
                }
            }
        }
        // Fail
        done = true;
        return;
    }
예제 #26
0
        public string Execute(Graph graph, string start, string end)
        {
            Vertex startVertex = null;
            Vertex endVertex   = null;

            //Find and set the start vertex to 0.
            if (graph.Vertices[0].Label != start)
            {
                startVertex = graph.Vertices.Find(p => p.Label == start);
            }
            else
            {
                startVertex = graph.Vertices[0];
            }
            startVertex.Distance = 0;

            MinHeap minHeap = new MinHeap();

            foreach (var v in graph.Vertices)
            {
                minHeap.Push(v);

                if (v.Label.Equals(end))
                {
                    endVertex = v;
                }
            }

            while (minHeap.Count() != 0)
            {
                //use the vertex with least distance
                Vertex vertex = minHeap.removeMinHeap();

                //skip is vertex already visited
                if (vertex.IsVisited)
                {
                    continue;
                }

                //if curren vertix distance is 'unlimited', stop.
                if (vertex.Distance == int.MaxValue)
                {
                    break;
                }

                //iterate through every neighboring vertice

                foreach (var edge in vertex.IncidentEdges)
                {
                    var AdjacentVertex = edge.VTwo;

                    //skip if vertex already visited
                    if (!AdjacentVertex.IsVisited)
                    {
                        int weight = edge.Weight;
                        if (vertex.Distance + weight < AdjacentVertex.Distance)
                        {
                            AdjacentVertex.Distance = vertex.Distance + weight;
                            //if distance+weight is lower than the neighboring, use that and set to parent/child dictionary
                            _path[AdjacentVertex] = vertex;
                            minHeap.Push(AdjacentVertex);
                        }
                    }
                }
                vertex.IsVisited = true;
            }

            //Finally, print the path into a string, repeat looking in the path dictionary
            //from the end vertex, setting it to the parent and then becoming the end
            //and print the parent until the parent becomes the start vertex again.
            string Path = endVertex.Label;

            while (true)
            {
                Vertex ParentVertex = _path[endVertex];
                Path = Path + " " + ParentVertex.Label;
                if (ParentVertex.Equals(startVertex))
                {
                    break;
                }
                endVertex = ParentVertex;
            }

            Path = Reverse(Path);
            Path = Path.Replace(" ", "->");
            return(Path);
        }