Esempio n. 1
1
        private static void MaxTest()
        {
            Console.WriteLine("This section is to test the MAX HEAP class.\n");

            string sort_error = "The current value is not less than the next value on the array.";
            string pop_error = "The current value is not grater than the next value on the array";
            string invariant_error = "The invariants have been broken.";

            MaxHeap<int> myHeap = new MaxHeap<int>();

            int[] numberList = new int[] { 2, 5, 9, 2, 8, 1, 4, 7, 3, 6 };

            Console.WriteLine("Adding the following numbers to the heap: [{0}]\n",
                string.Join(", ", numberList));

            foreach (int number in numberList)
                myHeap.Add(number);

            Console.WriteLine("New Heap: [{0}]\n", string.Join(", ", myHeap));

            Console.WriteLine("Performing Heap Sort...\n");

            myHeap.Sort();
            TestMaxSort(myHeap, sort_error);

            Console.WriteLine("New Heap: [{0}]\n", string.Join(", ", myHeap));

            Console.WriteLine("Rebuilding Heap...\n");

            myHeap.BuildHeap();

            Console.WriteLine("New Heap: [{0}]\n", string.Join(", ", myHeap));

            Console.WriteLine("Poping the top value until heap is empty...\n");

            TestMaxPop(myHeap, pop_error);

            int elements = 20000;
            myHeap = new MaxHeap<int>(elements);
            int[] random_list = RandomIntArray(elements);

            Console.WriteLine("Adding {0} values to a new heap and verifying the invariants...\n", elements);

            Console.WriteLine("This part will take a while...\n");

            foreach (int number in random_list)
            {
                myHeap.Add(number);
                TestMaxInvariant(myHeap, invariant_error);
            }

            Console.WriteLine("Heap too big to print on console, current elements in heap: {0}\n", myHeap.Count);

            Console.WriteLine("Going to pop half of the values out of the heap and verifying the invariants...\n");

            Console.WriteLine("Again... This part will take a while...\n");

            for (int i = 0; i < elements / 2; i++)
            {
                myHeap.PopMax();
                TestMaxInvariant(myHeap, invariant_error);
            }

            Console.WriteLine("Heap too big to print on console, current elements in heap: {0}\n", myHeap.Count);

            Console.WriteLine("----------------------------------------------------");
        }
Esempio n. 2
0
        // public int LastStoneWeight(int[] stones)
        // {
        //     var sortedList = stones.ToList();
        //     sortedList.Sort();
        //
        //     while (sortedList.Count > 1)
        //     {
        //         var newStone = Math.Abs(sortedList[^1] - sortedList[^2]);
        //         sortedList.RemoveAt(sortedList.Count - 1);
        //         sortedList.RemoveAt(sortedList.Count - 1);
        //         if (newStone != 0)
        //             sortedList.InsertIntoSortedList(newStone);
        //     }
        //
        //     return sortedList.Count switch
        //     {
        //         0 => 0,
        //         1 => sortedList[0],
        //         _ => 0
        //     };
        // }

        public int LastStoneWeight(int[] stones)
        {
            // Insert all the stones into a Max-Heap.
            MaxHeap <int> heap = new MaxHeap <int>();

            foreach (var stone in stones)
            {
                heap.Add(stone);
            }

            // While there is more than one stone left, we need to remove the two largest
            // and smash them together. If there is a resulting stone, we need to put into
            // the heap.
            while (heap.Count > 1)
            {
                var stone1 = heap.ExtractDominating();
                var stone2 = heap.ExtractDominating();
                if (stone1 != stone2)
                {
                    heap.Add(stone1 - stone2);
                }
            }

            // Check whether or not there is a stone left to return.
            return(heap.Count == 0 ? 0 : heap.ExtractDominating());
        }
Esempio n. 3
0
    public void AddNum(int num)
    {
        if (maxH.GetSize() > 0 && num >= maxH.Peek())   // If num is bigger than the 1st half it goes to the 2nd half
        {
            minH.Add(num);
        }
        else
        {
            maxH.Add(num);
        }

        if (Math.Abs(maxH.GetSize() - minH.GetSize()) > 1)   // If there are more than one number of difference
        {
            if (maxH.GetSize() > minH.GetSize())
            {
                int number = maxH.Pull();
                minH.Add(number);
            }
            else
            {
                int number = minH.Pull();
                maxH.Add(number);
            }
        }
    }
        public PointSet GetKNN(Point p, int K, DimWeight dw)
        {
            var pc   = new PointCompare(dw, p);
            var heap = new MaxHeap <Point>(pc);

            for (int i = 0; i < pointset.Points.Count(); i++)
            {
                if (heap.Count < K)
                {
                    heap.Add(pointset.Points[i]);
                }
                else if (pc.Compare(heap.GetMin(), pointset.Points[i]) > 0)
                {
                    heap.ExtractDominating();
                    heap.Add(pointset.Points[i]);
                }
            }

            PointSet ps = new PointSet(p.NumDim);

            while (heap.Count > 0)
            {
                ps.AddPoint(heap.ExtractDominating());
            }

            return(ps);
        }
        public int[][] KClosest(int[][] points, int K)
        {
            var heap = new MaxHeap(K);

            foreach (var point in points)
            {
                if (heap.Count < K)
                {
                    heap.Add(new Node(point));
                }
                else
                {
                    var dist = point[0] * point[0] + point[1] * point[1];
                    if (dist >= heap.Peek().Dist)
                    {
                        continue;
                    }
                    heap.Pop();
                    heap.Add(new Node(point));
                }
            }

            var result = new Stack <int[]>(K);

            while (heap.Count > 0)
            {
                result.Push(heap.Pop().Point);
            }

            return(result.ToArray());
        }
Esempio n. 6
0
        public static int Run(int[] input)
        {
            if (input == null || input.Length == 0)
            {
                throw new InvalidOperationException();
            }

            var root = input[0];

            var left  = new MaxHeap <int>();
            var right = new MinHeap <int>();

            for (var i = 1; i < input.Length; i++)
            {
                var current = input[i];
                if (current <= root)
                {
                    if (left.Count > right.Count)
                    {
                        if (left.GetRoot() > current)
                        {
                            right.Add(root);
                            root = left.Pop();
                            left.Add(current);
                        }
                        else
                        {
                            right.Add(root);
                            root = current;
                        }
                    }
                    else
                    {
                        left.Add(current);
                    }
                }
                else
                {
                    if (right.Count + 1 > left.Count)
                    {
                        if (right.GetRoot() < current)
                        {
                            left.Add(root);
                            root = right.Pop();
                            right.Add(current);
                        }
                        else
                        {
                            left.Add(root);
                            root = current;
                        }
                    }
                    else
                    {
                        right.Add(current);
                    }
                }
            }
            return(root);
        }
        public void TestRemove_TenItems()
        {
            MaxHeap <int> maxHeap = new MaxHeap <int>();
            int           items   = 10;

            maxHeap.Add(10);
            maxHeap.Add(1);
            maxHeap.Add(9);
            maxHeap.Add(2);
            maxHeap.Add(8);
            maxHeap.Add(3);
            maxHeap.Add(7);
            maxHeap.Add(4);
            maxHeap.Add(6);
            maxHeap.Add(5);

            StringBuilder actual = new StringBuilder();

            for (int i = 0; i < items; i++)
            {
                actual.Append(maxHeap.Remove());
            }

            string expected = "10987654321";

            Assert.AreEqual(expected, actual.ToString());
        }
Esempio n. 8
0
        public int LastStoneWeight(int[] stones)
        {
            // insert stones into max-heap
            // while heap.size() is greater than or equal to 2
            //   y = extract_max
            //   x = extract_max
            //   diff = y-x
            //   if (diff > 0), insert diff into heap

            var heap = new MaxHeap(stones.Length);

            foreach (var stone in stones)
            {
                heap.Add(stone);
            }

            int x, y, diff;

            while (heap.Size() >= 2)
            {
                y    = heap.Poll();
                x    = heap.Poll();
                diff = Math.Abs(y - x);
                if (diff > 0)
                {
                    heap.Add(diff);
                }
            }

            return(heap.Peek());
        }
        public void TestComparer()
        {
            MaxHeap <int> maxHeap = new MaxHeap <int>(new ReverseIntComparer());
            int           items   = 10;

            maxHeap.Add(10);
            maxHeap.Add(1);
            maxHeap.Add(9);
            maxHeap.Add(2);
            maxHeap.Add(8);
            maxHeap.Add(3);
            maxHeap.Add(7);
            maxHeap.Add(4);
            maxHeap.Add(6);
            maxHeap.Add(5);

            StringBuilder actual = new StringBuilder();

            for (int i = 0; i < items; i++)
            {
                actual.Append(maxHeap.Remove());
            }

            string expected = "12345678910";

            Assert.AreEqual(expected, actual.ToString());
        }
Esempio n. 10
0
        public int[][] KClosest(int[][] points, int k)
        {
            int     n     = points.Length;
            var     dists = new double[n];
            MaxHeap heap  = new MaxHeap(k);


            for (int i = 0; i < n; i++)
            {
                dists[i] = Math.Sqrt(points[i][0] * points[i][0] + points[i][1] * points[i][1]);
                if (heap.Add(dists[i]))
                {
                    continue;
                }
                else if (heap.GetMax() > dists[i])
                {
                    heap.ExtractMax();
                    heap.Add(dists[i]);
                }
            }
            var disk = heap.GetMax();

            int[][] ans = new int[k][];
            int     t   = 0;

            for (int i = 0; i < n; i++)
            {
                var dis = Math.Sqrt(points[i][0] * points[i][0] + points[i][1] * points[i][1]);
                if (dis <= disk)
                {
                    ans[t++] = points[i];
                }
            }
            return(ans);
        }
Esempio n. 11
0
        public void Ctor1Test()
        {
            var heap = new MaxHeap <int>();

            heap.Add(3);
            heap.Add(10);

            Assert.AreEqual(10, heap.Max);
        }
Esempio n. 12
0
        public void Ctor2Test()
        {
            var heap = new MaxHeap <int>(Comparer <int> .Create((x, y) => x * x - y * y));

            heap.Add(3);
            heap.Add(-4);

            Assert.AreEqual(-4, heap.Max);
        }
Esempio n. 13
0
        // 6
        public static void D_ConstructingTheArray()
        {
            int    t;
            string s = Console.ReadLine().Trim();

            t = int.Parse(s);

            for (int j = 0; j < t; j++)
            {
                s = Console.ReadLine().Trim();
                int   n = int.Parse(s);
                int[] a = new int[n];

                if (n == 1)
                {
                    Console.WriteLine(1);
                    continue;
                }


                MaxHeap <Interval> heap = new MaxHeap <Interval>(new IntervalComparer());
                heap.Add(new Interval {
                    l = 0, r = n - 1, len = n
                });
                int counter = 1;
                while (heap.Count > 0)
                {
                    Interval v = heap.ExtractDominating();
                    if (v.len < 1)
                    {
                        continue;
                    }
                    int ind = (v.l + v.r) / 2;
                    a[ind] = counter;
                    counter++;
                    if (v.len > 1)
                    {
                        var v1 = new Interval
                        {
                            l = v.l,
                            r = ind - 1
                        };
                        var v2 = new Interval
                        {
                            l = ind + 1,
                            r = v.r
                        };
                        v1.len = v1.r - v1.l + 1;
                        v2.len = v2.r - v2.l + 1;
                        heap.Add(v1);
                        heap.Add(v2);
                    }
                }
                Console.WriteLine(PrintList(a));
            }
        }
        private void AddTest()
        {
            MaxHeap maxHeap = new MaxHeap(100);

            maxHeap.Add(4);
            maxHeap.Add(9);
            maxHeap.Add(5);
            Assert.AreEqual(3, maxHeap.Count);
            Assert.AreEqual()
        }
Esempio n. 15
0
        public void TestCount(int[] values, int expected)
        {
            for (int i = 0; i < values.Length; i++)
            {
                sut.Add(values[i]);
            }
            var actual = sut.Count;

            Assert.Equal(expected, actual);
        }
Esempio n. 16
0
        // Use Prim's algorithm to generate a MST of edges.
        private IEnumerable <Edge> TrimEdges(ICollection <int>[] adjacency, IList <Room> rooms)
        {
            // Comparator for MapVertex is defined to give negated, so this is actually a minheap
            MaxHeap <MapVertex> pq = new MaxHeap <MapVertex>(rooms.Count);

            var(firstX, firstY) = rooms[0].Center;
            pq.Add(new MapVertex(0, firstX, firstY, 0));

            bool[]   inMst  = new bool[rooms.Count];
            double[] weight = new double[rooms.Count];
            int[]    parent = new int[rooms.Count];

            for (int i = 0; i < rooms.Count; i++)
            {
                weight[i] = double.MaxValue;
                parent[i] = -1;
            }

            while (pq.Count > 0)
            {
                MapVertex min = pq.PopMax();
                inMst[min.ID] = true;

                foreach (int neighborID in adjacency[min.ID])
                {
                    if (inMst[neighborID])
                    {
                        continue;
                    }

                    var(neighborX, neighborY) = rooms[neighborID].Center;
                    double newWeight = Distance.EuclideanDistanceSquared(min.X, min.Y,
                                                                         neighborX, neighborY);

                    if (weight[neighborID] > newWeight)
                    {
                        weight[neighborID] = newWeight;
                        pq.Add(new MapVertex(neighborID, neighborX, neighborY, newWeight));
                        parent[neighborID] = min.ID;
                    }
                }
            }

            ICollection <Edge> graph = new HashSet <Edge>();

            for (int i = 0; i < rooms.Count; i++)
            {
                if (parent[i] != -1)
                {
                    graph.Add(new Edge(i, parent[i]));
                }
            }

            return(graph);
        }
        public void GetMaxTest()
        {
            var heap = new MaxHeap <int, int>();

            heap.Add(42, -1);
            heap.Add(5, 6);
            var max = heap.Max;

            Assert.AreEqual(5, max.Key);
            Assert.AreEqual(6, max.Value);
        }
Esempio n. 18
0
 public void TestExtractAndCount()
 {
     var maxHeap = new MaxHeap<string>();
     maxHeap.Add("Ivan");
     maxHeap.Add("George");
     var expected = "Pesho";
     maxHeap.Add(expected);
     var actual = maxHeap.ExtractDominating();
     Assert.AreEqual(expected, actual);
     Assert.AreEqual(2, maxHeap.Count);
 }
Esempio n. 19
0
        private MaxHeap <int> getExampleHeap()
        {
            MaxHeap <int> h = new MaxHeap <int>();

            h.Add(4);
            h.Add(5);
            h.Add(3);
            h.Add(1);
            h.Add(2);
            return(h);
        }
        public void TestPeek_NonEmptyHeap()
        {
            MaxHeap <int> maxHeap = new MaxHeap <int>();

            maxHeap.Add(5);
            maxHeap.Add(90);
            maxHeap.Add(15);
            maxHeap.Add(89);

            Assert.AreEqual(90, maxHeap.Peek());
        }
Esempio n. 21
0
        static void GetMedian(Stream ip)
        {
            int val;

            MinHeap <int> rHeap = new MinHeap <int>();
            MaxHeap <int> lHeap = new MaxHeap <int>();

            double runningMedian = 0.0;

            while ((val = ip.Next()) != -1)
            {
                if (rHeap.Count == lHeap.Count)
                {
                    if (val < runningMedian)
                    {
                        lHeap.Add(val);
                        runningMedian = lHeap.Peek();
                    }
                    else
                    {
                        rHeap.Add(val);
                        runningMedian = rHeap.Peek();
                    }
                }
                else if (lHeap.Count > rHeap.Count)
                {
                    if (val < runningMedian)
                    {
                        rHeap.Add(lHeap.Delete());
                        lHeap.Add(val);
                    }
                    else
                    {
                        rHeap.Add(val);
                    }

                    runningMedian = (lHeap.Peek() + rHeap.Peek()) / 2.0;
                }
                else
                {
                    if (val < runningMedian)
                    {
                        lHeap.Add(val);
                    }
                    else
                    {
                        lHeap.Add(rHeap.Delete());
                        rHeap.Add(val);
                    }

                    runningMedian = (lHeap.Peek() + rHeap.Peek()) / 2.0;
                }
            }
        }
        public void Add8_6_5_3_4()
        {
            var maxHeap = new MaxHeap <int>();

            maxHeap.Add(8);
            maxHeap.Add(6);
            maxHeap.Add(5);
            maxHeap.Add(3);
            maxHeap.Add(4);

            Assert.AreEqual(5, maxHeap.Count);
        }
        public void WhenMaxHeap_ThenThePeekNodeMustBeTheMaxElement()
        {
            var maxHeap = new MaxHeap <int>();

            maxHeap.Add(3);
            maxHeap.Add(1);
            maxHeap.Add(4);
            maxHeap.Add(2);
            maxHeap.Add(5);

            Assert.AreEqual(5, maxHeap.Peek());
        }
        public void TestClear()
        {
            MaxHeap <int> maxHeap = new MaxHeap <int>();

            maxHeap.Add(1);
            maxHeap.Add(2);
            maxHeap.Add(3);

            maxHeap.Clear();
            Assert.AreEqual(0, maxHeap.Count);
            maxHeap.Peek();
        }
 private void CheckPoint(int K, MaxHeap <Point> heap, PointCompare pc)
 {
     if (heap.Count < K)
     {
         heap.Add(point);
     }
     else if (pc.Compare(heap.GetMin(), point) > 0)
     {
         heap.ExtractDominating();
         heap.Add(point);
     }
 }
Esempio n. 26
0
        private List <Tuple <int, int> > GenerateSkyline(int[][] input, List <Tuple <int, int, int> > horizontalList)
        {
            var result = new List <Tuple <int, int> >();

            horizontalList.Sort();
            var hasStarted = new bool[input.Length];
            var maxHeap    = new MaxHeap <Tuple <int, int, bool> >();

            for (int i = 0; i < horizontalList.Count; i++)
            {
                var coord = horizontalList[i];
                if (hasStarted[coord.Item3])
                {
                    var target = new Tuple <int, int, bool>(coord.Item2, coord.Item3, true);
                    if (maxHeap.Contains(target))
                    {
                        // remove this from heap and log start //
                        maxHeap.Remove(target);
                        result.Add(new Tuple <int, int>(input[coord.Item3][0], input[coord.Item3][2]));
                    }
                    else
                    {
                        maxHeap.Remove(new Tuple <int, int, bool>(coord.Item2, coord.Item3, false));
                    }

                    // log end
                    if (maxHeap.Count == 0)
                    {
                        result.Add(new Tuple <int, int>(coord.Item1, 0));
                    }
                    else if (coord.Item2 > maxHeap.Peek().Item1)
                    {
                        result.Add(new Tuple <int, int>(coord.Item1, maxHeap.Peek().Item1));
                    }
                }
                else
                {
                    if (maxHeap.Count == 0 || maxHeap.Peek().Item1 < coord.Item2)
                    {
                        maxHeap.Add(new Tuple <int, int, bool>(coord.Item2, coord.Item3, true));
                    }
                    else
                    {
                        maxHeap.Add(new Tuple <int, int, bool>(coord.Item2, coord.Item3, false));
                    }

                    hasStarted[coord.Item3] = true;
                }
            }

            return(result);
        }
Esempio n. 27
0
        public void AddEmptyRemove()
        {
            var heap = new MaxHeap();

            heap.Add(10);
            Assert.AreEqual(10, heap.Peek());

            var res = heap.Pop();

            Assert.AreEqual(10, res);
            heap.Add(20);
            Assert.AreEqual(20, heap.Peek());
        }
        public void WhenPollElement_ThenNextMaxElementUp()
        {
            var maxHeap = new MaxHeap <int>();

            maxHeap.Add(3);
            maxHeap.Add(1);
            maxHeap.Add(4);
            maxHeap.Add(2);
            maxHeap.Add(5);
            maxHeap.Poll();

            Assert.AreEqual(4, maxHeap.Peek());
        }
    public void ExecuteMaxHeap()
    {
        MaxHeap myHeap = new MaxHeap();

        myHeap.Add(1);
        myHeap.Add(6);
        myHeap.Add(3);

        value = myHeap.PopMax();
        Console.WriteLine(value);

        value = myHeap.PopMax();
        Console.WriteLine(value);
    }
Esempio n. 30
0
    public void HeapWorks() {
      var heap = new MaxHeap<int>();
      heap.Add(5);
      heap.Add(6);
      heap.Add(4);
      heap.Add(1);
      heap.Add(-1);

      Assert.AreEqual(6, heap.Remove());
      Assert.AreEqual(5, heap.Remove());
      Assert.AreEqual(4, heap.Remove());
      Assert.AreEqual(1, heap.Remove());
      Assert.AreEqual(-1, heap.Remove());
    }
Esempio n. 31
0
        //https://leetcode.com/problems/ipo/
        public int FindMaximizedCapital(int k, int W, int[] Profits, int[] Capital)
        {
            var projects = new List <Project>(Profits.Length);

            for (int i = 0; i < Profits.Length; i++)
            {
                projects.Add(new Project(Profits[i], Capital[i]));
            }
            var projectsByCapital = projects.OrderBy(x => x.Capital).ToArray();
            var projectIndex      = 0;
            var currentCandidates = new MaxHeap <Project>(new Project(0, int.MaxValue));

            while (projectIndex < projectsByCapital.Length)
            {
                if (projectsByCapital[projectIndex].Capital <= W)
                {
                    currentCandidates.Add(projectsByCapital[projectIndex]);
                }
                else
                {
                    break;
                }
                projectIndex++;
            }

            while (k > 0 && currentCandidates.Count > 0)
            {
                var bestProject = currentCandidates.ExtractMax();
                if (bestProject.Capital > W)
                {
                    break;
                }
                W += bestProject.Profit;
                while (projectIndex < projectsByCapital.Length)
                {
                    if (projectsByCapital[projectIndex].Capital <= W)
                    {
                        currentCandidates.Add(projectsByCapital[projectIndex]);
                    }
                    else
                    {
                        break;
                    }
                    projectIndex++;
                }
                k--;
            }

            return(W);
        }
        private void NoCapacityTest()
        {
            MaxHeap maxHeap = new MaxHeap(1);

            try
            {
                maxHeap.Add(3);
                maxHeap.Add(5);
                Assert.Fail();
            }
            catch (Exception)
            {
            }
        }
        public void Add_Two_Elements_And_Remove_Top()
        {
            var maxHeap = new MaxHeap <int>();

            maxHeap.Add(8);
            maxHeap.Add(10);

            Assert.AreEqual(2, maxHeap.Count);

            var top = maxHeap.RemoveTop();

            Assert.AreEqual(10, top);

            Assert.AreEqual(1, maxHeap.Count);
        }
Esempio n. 34
0
        public static IEnumerable<int> GetMedians(IEnumerable<int> sequence)
        {
            var enumerator = sequence.GetEnumerator();

            var smallestNumbers = new MaxHeap<int>();
            var largestNumbers = new MinHeap<int>();

            if (enumerator.MoveNext())
            {
                var number = enumerator.Current;
                smallestNumbers.Add(number);
                yield return smallestNumbers.Max;
            }

            while (enumerator.MoveNext())
            {
                var number = enumerator.Current;
                if (smallestNumbers.Count <= largestNumbers.Count)
                {
                    if (number > largestNumbers.Min)
                    {
                        var min = largestNumbers.ExtractMin();
                        smallestNumbers.Add(min);
                        largestNumbers.Add(number);
                    }
                    else
                    {
                        smallestNumbers.Add(number);
                    }
                }
                else
                {
                    if (number < smallestNumbers.Max)
                    {
                        var max = smallestNumbers.ExtractMax();
                        largestNumbers.Add(max);
                        smallestNumbers.Add(number);
                    }
                    else
                    {
                        largestNumbers.Add(number);
                    }
                }

                yield return smallestNumbers.Max;
            }
        }