Beispiel #1
0
        private static Heap.Heap GetLevelWiseNodes(TreeNode root, int level)
        {
            if (root == null)
            {
                return(null);
            }

            Heap.Heap heapResult = new Heap.Heap(Convert.ToInt32(Math.Pow(2, level - 1)), Heap.Heap.Type.Min);
            if (level == 1)
            {
                heapResult.Insert(root.Data);
            }
            else if (level > 1)
            {
                Heap.Heap subResult1 = GetLevelWiseNodes(root.Left, level - 1);
                Heap.Heap subResult2 = GetLevelWiseNodes(root.Right, level - 1);

                while (subResult1.count > 0)
                {
                    heapResult.Insert(subResult1.Delete());
                }
                while (subResult2.count > 0)
                {
                    heapResult.Insert(subResult2.Delete());
                }
            }

            return(heapResult);
        }
Beispiel #2
0
        public static void Main()
        {
            Heap heap = new Heap();
            int  iter = 0;

            while (iter != 9)
            {
                Console.Clear();
                Console.WriteLine("Witaj, którą czynność chcesz wykonać:");
                Console.WriteLine("1.Wypełnij kopiec (1000 losowych wartosci z zakresu 0-1000)");
                Console.WriteLine("2.Usuń największą wartość w kopcu");
                Console.WriteLine("3.Wyświetl kopiec");
                Console.WriteLine("Wyjdź do menu głównego");
                heap.Check();
                if (!Int32.TryParse(Console.ReadLine(), out iter))
                {
                    continue;
                }
                if (iter == 1)
                {
                    Random RandomNumber = new Random();
                    for (int i = 0; i < 1000; i++)
                    {
                        heap.Insert(RandomNumber.Next(1000));
                    }
                }
                if (iter == 2)
                {
                    heap.DeleteMax();
                }
                if (iter == 3)
                {
                    heap.DispData(heap);
                }

                Console.ReadLine();
            }
        }
 public void Enqueue(int item)
 {
     heap.Insert(item);
 }
 public void Enqueue(int value)
 {
     heap.Insert(value);
 }
Beispiel #5
0
        static void Main(string[] args)
        {
            // ------------------------ test instance (begin)
            string[] names                   = new string[] { "Kelly", "Cindy", "John", "Andrew", "Richard", "Michael", "Guy", "Elicia", "Tom", "Iman", "Simon", "Vicky", "Kevin", "David" };
            int[]    IDs                     = new int[] { 1, 6, 5, 7, 8, 3, 10, 4, 2, 9, 14, 12, 11, 13 };
            int[]    certificateAdd          = new int[] { 1, 2, 3, 4, 5, 3, 7, 2, 2, 10, 11, 12, 13, 14 };
            int[]    certificateDelete       = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };
            int[]    certificateMinHeapBuild = new int[] { 1, 8, 6, 9, 5, 3, 7, 4, 2, 10, 11, 12, 13, 14 };
            int[]    certificateMaxHeapBuild = new int[] { 11, 10, 14, 4, 5, 12, 7, 8, 9, 2, 1, 6, 13, 3 };
            // ------------------------ test instance (end)


            Heap <int, string> minHeap = null;
            Heap <int, string> maxHeap = null;

            IHeapifyable <int, string>[] nodes = null;
            string result = "";

            // test 1
            try
            {
                Console.WriteLine("\n\nTest A: Create a min-heap by calling 'minHeap = new Heap<int, string>(new IntAscendingComparer());'");
                minHeap = new Heap <int, string>(new IntAscendingComparer());
                Console.WriteLine(" :: SUCCESS: min-heap's state " + minHeap.ToString());
                result = result + "A";
            }
            catch (Exception exception)
            {
                try { Console.WriteLine(" :: FAIL: min-heap's state " + minHeap.ToString()); } catch { };
                Console.WriteLine(exception.ToString());
                result = result + "-";
            }

            // test 2
            try
            {
                Console.WriteLine("\n\nTest B: Run a sequence of operations: ");

                for (int i = 0; i < Math.Min(names.Length, IDs.Length); i++)
                {
                    Console.WriteLine("\nInsert a node with name {0} (data) and ID {1} (key).", names[i], IDs[i]);
                    IHeapifyable <int, string> node = minHeap.Insert(IDs[i], names[i]);
                    if (!(node.Position == certificateAdd[i] && minHeap.Count == i + 1))
                    {
                        throw new Exception("The min-heap has a wrong structure");
                    }
                    Console.WriteLine(" :: SUCCESS: min-heap's state " + minHeap.ToString());
                }
                result = result + "B";
            }
            catch (Exception exception)
            {
                try { Console.WriteLine(" :: FAIL: min-heap's state " + minHeap.ToString()); } catch { };
                Console.WriteLine(exception.ToString());
                result = result + "-";
            }

            // test 3
            try
            {
                Console.WriteLine("\n\nTest C: Run a sequence of operations: ");

                for (int i = 0; i < certificateDelete.Length; i++)
                {
                    Console.WriteLine("\nDelete the minimum element from the min-heap.");
                    IHeapifyable <int, string> node = minHeap.Delete();
                    if (node.Key != certificateDelete[i])
                    {
                        throw new Exception("The extracted node has a wrong key");
                    }
                    if (minHeap.Count != certificateDelete.Length - i - 1)
                    {
                        throw new Exception("The heap has a wrong number of elements");
                    }
                    if (certificateDelete.Length - i - 1 > 0)
                    {
                        if ((minHeap.Min().Key != certificateDelete[i + 1]) && (minHeap.Min().Position != 1))
                        {
                            throw new Exception("The min-heap has a wrong structure");
                        }
                    }
                    Console.WriteLine(" :: SUCCESS: min-heap's state " + minHeap.ToString());
                }
                result = result + "C";
            }
            catch (Exception exception)
            {
                try { Console.WriteLine(" :: FAIL: min-heap's state " + minHeap.ToString()); } catch { };
                Console.WriteLine(exception.ToString());
                result = result + "-";
            }

            // test 4
            try
            {
                Console.WriteLine("\n\nTest D: Delete the minimum element from the min-heap.");
                IHeapifyable <int, string> node = minHeap.Delete();
                Console.WriteLine("Last operation is invalid and must throw InvalidOperationException. Your solution does not match specification.");
                result = result + "-";
            }
            catch (InvalidOperationException)
            {
                Console.WriteLine(" :: SUCCESS: InvalidOperationException is thrown because the min-heap is empty");
                result = result + "D";
            }
            catch (Exception)
            {
                Console.WriteLine(" :: FAIL: min-heap's state " + minHeap.ToString());
                Console.WriteLine("Last operation is invalid and must throw InvalidOperationException. Your solution does not match specification.");
                result = result + "-";
            }

            // test 5
            try
            {
                Console.WriteLine("\n\nTest E: Run a sequence of operations: ");
                Console.WriteLine("\nInsert a node with name {0} (data) and ID {1} (key).", names[0], IDs[0]);
                IHeapifyable <int, string> node = minHeap.Insert(IDs[0], names[0]);
                Console.WriteLine(" :: SUCCESS: min-heap's state " + minHeap.ToString());

                Console.WriteLine("\nBuild the min-heap for the pair of key-value arrays with \n[{0}] as keys and \n[{1}] as data elements", String.Join(", ", IDs), String.Join(", ", names));
                nodes = minHeap.BuildHeap(IDs, names);
                Console.WriteLine("Last operation is invalid and must throw InvalidOperationException. Your solution does not match specification.");
                result = result + "-";
            }
            catch (InvalidOperationException)
            {
                Console.WriteLine(" :: SUCCESS: InvalidOperationException is thrown because the min-heap is not empty");
                result = result + "E";
            }
            catch (Exception)
            {
                Console.WriteLine(" :: FAIL: min-heap's state " + minHeap.ToString());
                Console.WriteLine("Last operation is invalid and must throw InvalidOperationException. Your solution does not match specification.");
                result = result + "-";
            }

            // test 6
            try
            {
                Console.WriteLine("\n\nTest F: Run a sequence of operations: ");

                Console.WriteLine("\nClear the min-heap.");
                minHeap.Clear();
                Console.WriteLine(" :: SUCCESS: min-heap's state " + minHeap.ToString());
                Console.WriteLine("\nBuild the min-heap for the pair of key-value arrays with \n[{0}] as keys and \n[{1}] as data elements", String.Join(", ", IDs), String.Join(", ", names));
                nodes = minHeap.BuildHeap(IDs, names);
                if (minHeap.Count != certificateMinHeapBuild.Length)
                {
                    throw new Exception("The resulting min-heap has a wrong number of elements.");
                }
                if (nodes.Length != certificateMinHeapBuild.Length)
                {
                    throw new Exception("The size of the resulting array returned by BuildHeap() is incorrect.");
                }
                for (int i = 0; i < nodes.Length; i++)
                {
                    if (!(nodes[i].Position == certificateMinHeapBuild[i]))
                    {
                        throw new Exception("The min-heap has a wrong structure");
                    }
                }
                result = result + "F";
                Console.WriteLine(" :: SUCCESS: min-heap's state " + minHeap.ToString());
            }
            catch (Exception exception)
            {
                try { Console.WriteLine(" :: FAIL: min-heap's state " + minHeap.ToString()); } catch { };
                Console.WriteLine(exception.ToString());
                result = result + "-";
            }


            // test 7
            try
            {
                Console.WriteLine("\n\nTest G: Run a sequence of operations: ");

                IHeapifyable <int, string> node = nodes[nodes.Length - 1];

                Console.WriteLine("\nDelete the minimum element from the min-heap.");
                minHeap.Delete();
                Console.WriteLine(" :: SUCCESS: min-heap's state " + minHeap.ToString());
                Console.WriteLine("\nDelete the minimum element from the min-heap.");
                minHeap.Delete();
                Console.WriteLine(" :: SUCCESS: min-heap's state " + minHeap.ToString());

                Console.WriteLine("\nRun DecreaseKey(node,0) for node {0} by setting the new value of its key to 0", node);
                minHeap.DecreaseKey(node, 0);

                if (minHeap.Count != certificateMinHeapBuild.Length - 2)
                {
                    throw new Exception("The resulting min-heap has a wrong number of elements");
                }
                if (!((node.Position == 1) && (minHeap.Min().Key == node.Key)))
                {
                    throw new Exception("The min-heap has a wrong structure");
                }
                Console.WriteLine(" :: SUCCESS: min-heap's state " + minHeap.ToString());
                result = result + "G";
            }
            catch (Exception exception)
            {
                try { Console.WriteLine(" :: FAIL: min-heap's state " + minHeap.ToString()); } catch { };
                Console.WriteLine(exception.ToString());
                result = result + "-";
            }


            // test 8
            try
            {
                Console.WriteLine("\n\nTest H: Run a sequence of operations: ");
                Console.WriteLine("\nCreate a max-heap by calling 'maxHeap = new Heap<int, string>(new IntDescendingComparer());'");
                maxHeap = new Heap <int, string>(new IntDescendingComparer());
                Console.WriteLine(" :: SUCCESS: max-heap's state " + maxHeap.ToString());
                Console.WriteLine("\nBuild the max-heap for the pair of key-value arrays with \n[{0}] as keys and \n[{1}] as data elements", String.Join(", ", IDs), String.Join(", ", names));
                nodes = maxHeap.BuildHeap(IDs, names);
                if (maxHeap.Count != certificateMaxHeapBuild.Length)
                {
                    throw new Exception("The resulting  max-heap has a wrong number of elements");
                }
                if (nodes.Length != certificateMaxHeapBuild.Length)
                {
                    throw new Exception("The size of the resulting array returned by BuildHeap() is incorrect.");
                }
                for (int i = 0; i < nodes.Length; i++)
                {
                    if (!(nodes[i].Position == certificateMaxHeapBuild[i]))
                    {
                        throw new Exception("The  max-heap has a wrong structure");
                    }
                }
                result = result + "H";
                Console.WriteLine(" :: SUCCESS: max-heap's state " + maxHeap.ToString());
            }
            catch (Exception exception)
            {
                try { Console.WriteLine(" :: FAIL:  max-heap's state " + maxHeap.ToString()); } catch { };
                Console.WriteLine(exception.ToString());
                result = result + "-";
            }

            Console.WriteLine("\n\n ------------------- SUMMARY ------------------- ");
            Console.WriteLine("Tests passed: " + result);
            Console.ReadKey();
        }
Beispiel #6
0
        public void Main()
        {
            int  value, value2;
            Heap theHeap = new Heap(31);
            bool success;

            theHeap.Insert(70);
            theHeap.Insert(40);
            theHeap.Insert(50);
            theHeap.Insert(20);
            theHeap.Insert(60);
            theHeap.Insert(100);
            theHeap.Insert(80);
            theHeap.Insert(30);
            theHeap.Insert(10);
            theHeap.Insert(90);

            var choise = "s";  // s-enter, i-insert, r-remove, c-change priority

            switch (choise)
            {
            case "s":
                theHeap.Display();
                break;

            case "i":
                var newValue = (new Random()).Next(1, 100);
                success = theHeap.Insert(newValue);
                if (!success)
                {
                    Console.WriteLine("Can't insert: the heap is full");
                    break;
                }
                break;

            case "r":
                if (!theHeap.IsEmpty())
                {
                    theHeap.Remove();
                }
                else
                {
                    Console.WriteLine("Can't remove: the heap full");
                }
                break;

            case "c":
                value   = (new Random()).Next(1, 5);
                value2  = (new Random()).Next(2, 3);
                success = theHeap.Change(value, value2);
                if (!success)
                {
                    Console.WriteLine("Invalid index");
                }
                break;

            default:
                break;
            }
        }
Beispiel #7
0
        static void Main(string[] args)
        {
            var heap = new Heap.Heap(4, HeapType.MinHeap);

            while (true)
            {
                Console.WriteLine("");
                Console.WriteLine("Choose an Options");
                Console.WriteLine("1. Insert Element");
                Console.WriteLine("2. Extract Top");
                Console.WriteLine("3. Peek");
                Console.WriteLine("4. HeapSize");
                Console.WriteLine("5. Print");
                Console.WriteLine("6. Exit");
                var option = Console.ReadLine();
                Console.WriteLine("");
                switch (option)
                {
                case "1":
                {
                    Console.Write("Enter Value : ");
                    var value = Console.ReadLine();
                    heap.Insert(Convert.ToInt32(value));
                    break;
                }

                case "2":
                {
                    Console.WriteLine("Extracted Top : " + heap.ExtractTop());
                    break;
                }

                case "3":
                {
                    Console.WriteLine("Peek : " + heap.Peek);
                    break;
                }

                case "4":
                {
                    Console.WriteLine("HeapSize : " + heap.HeapSize);
                    break;
                }

                case "5":
                {
                    Console.Write("Heap Data : ");
                    foreach (var data in heap.HeapData)
                    {
                        Console.Write(data);
                        Console.Write(" ");
                    }
                    break;
                }

                case "6":
                {
                    return;
                }
                }
            }
        }
Beispiel #8
0
        static void Main(string[] args)
        {
            // myHeap1 for Sort test
            Heap myHeap1 = new Heap();
            myHeap1.Insert(20);
            myHeap1.Insert(32);
            myHeap1.Insert(2);
            myHeap1.Insert(25);
            myHeap1.Insert(35);
            myHeap1.Insert(814);
            myHeap1.Insert(-5);
            myHeap1.Insert(0);
            myHeap1.Insert(16);
            myHeap1.Insert(77);

            myHeap1.Sort();
            for (int i = 0; i < myHeap1.heapIndex; i++)
                Debug.Assert(myHeap1[i] < myHeap1[i + 1]);

            // myHeap2 Insert and RemoveMax tests
            Heap myHeap2 = new Heap();
            myHeap2.Insert(65);
            myHeap2.Insert(35);
            myHeap2.Insert(9);
            myHeap2.Insert(272);
            myHeap2.Insert(6245);
            myHeap2.Insert(30);
            myHeap2.Insert(918);
            myHeap2.Insert(4);
            myHeap2.Insert(-6);
            myHeap2.Insert(1);

            int currRemoval = myHeap2.RemoveMax();
            while (myHeap2.heapIndex > 1)
            {
                int lastRemoval = currRemoval;
                currRemoval = myHeap2.RemoveMax();
                Debug.Assert(lastRemoval > currRemoval);
            }
        }