public void GivenAQueueWith1And3Enqueued_WhenEnqueue2_ShouldEnqueueThisNewValueOnMiddle()
        {
            // Arrange
            var queue = new MyPriorityQueue(3);

            queue.Enqueue(1);
            queue.Enqueue(3);

            // Act
            queue.Enqueue(2);

            // Assert
            queue.Dequeue().Should().Be(1);
            queue.Dequeue().Should().Be(2);
            queue.Dequeue().Should().Be(3);
        }
        public void GivenAQueueWithSomeItems_WhenTryToEnqueueANewValueThatIsGreaterThanAll_ShouldEnqueueThisLast()
        {
            // Arrange
            var queue = new MyPriorityQueue(3);

            queue.Enqueue(1);
            queue.Enqueue(2);

            // Act
            queue.Enqueue(3);

            // Assert
            queue.Dequeue().Should().Be(1);
            queue.Dequeue().Should().Be(2);
            queue.Dequeue().Should().Be(3);
        }
Exemple #3
0
        static void Main()
        {
            var people = new MyPriorityQueue <Person>();

            people.Enqueue(new Person("Doncho", 25));
            people.Enqueue(new Person("Niki", 24));
            people.Enqueue(new Person("Ivo", 25));
            people.Enqueue(new Person("Asya", 22));
            people.Enqueue(new Person("Pesho", int.MinValue));

            while (people.Count > 0)
            {
                Console.WriteLine(people.Dequeue());
            }
        }
Exemple #4
0
    public static void ShortestPath(SqlInt64 startNode, SqlInt64 endNode, SqlInt32 maxNodesToCheck, out SqlString pathResult, out SqlDouble distResult)
    {
        Dictionary <long, double> distance  = new Dictionary <long, double>(); // curr shortest distance (double) from startNode to (key) node
        Dictionary <long, long>   previous  = new Dictionary <long, long>();   // predecessor values to construct the actual path when done
        Dictionary <long, bool>   beenAdded = new Dictionary <long, bool>();   // has node been added to the queue yet? Once added, we don't want to add again

        long startNodeAsLong      = (long)startNode;
        long endNodeAsLong        = (long)endNode;
        int  maxNodesToCheckAsInt = (int)maxNodesToCheck;

        MyPriorityQueue PQ = new MyPriorityQueue();

        //initialize start node
        distance[startNodeAsLong] = 0.0;                    // distance from start node to itself is 0
        previous[startNodeAsLong] = -1;                     // -1 is the code for undefined.
        PQ.Enqueue(new NodeDistance(startNodeAsLong, 0.0)); // the queue holds distance information because Enqueue and Dequeue need it to keep queue ordered by priority. alt approach would be to store only node IDs and then do a distance lookup
        beenAdded[startNodeAsLong] = true;

        double alt = 0.0; //'test distance'

        try
        {
            while (PQ.Count() > 0 && beenAdded.Count < maxNodesToCheckAsInt)
            {
                NodeDistance u = PQ.Dequeue();// node with shortest distance from start
                if (u.nodeID == endNode)
                {
                    break;// found the target end node
                }
                //fetch all neighbors (v) of u

                List <Tuple <long, double> > neighbors = new List <Tuple <long, double> >();
                neighbors = FetchNeighbors(u.nodeID);


                foreach (var v in neighbors)                                    // if there are no neighbors, this loop will exit immediately
                {
                    if (beenAdded.ContainsKey(v.Item1) == false)                //first appearance of node v
                    {
                        distance[v.Item1] = double.MaxValue;                    //stand-in for infinity
                        previous[v.Item1] = -1;                                 //undefined
                        PQ.Enqueue(new NodeDistance(v.Item1, double.MaxValue)); //maxValue is a dummy value
                        beenAdded[v.Item1] = true;
                    }

                    //alt = distance[u.nodeID] + 1.0;  // if all edge weights are just hops can simplify to this
                    alt = distance[u.nodeID] + v.Item2; // alt = dist(start-to-u) + dist(u-to-v), so alt is total distance from start to v

                    if (alt < distance[v.Item1])        // is alt a new, shorter distance from start to v?
                    {
                        distance[v.Item1] = alt;
                        previous[v.Item1] = u.nodeID;
                        PQ.ChangePriority(v.Item1, alt);  // this will change the distance/priority
                    }
                }
            }

            // extract the shortest path as a string from the previous[] array
            pathResult = "NOTREACHABLE";                     // default result string
            distResult = -1.0;                               // distance result defaults to -1 == unreachable

            if (distance.ContainsKey(endNodeAsLong) == true) // endNode was encountered at some point in the algorithm
            {
                double sp = distance[endNodeAsLong];         // shortest path distance
                if (sp != double.MaxValue)                   // we have a reachable path
                {
                    pathResult = "";
                    long currNode = endNodeAsLong;
                    while (currNode != startNodeAsLong)  // construct the path as  semicolon delimited string
                    {
                        pathResult += currNode.ToString() + ";";
                        currNode    = previous[currNode];
                    }
                    pathResult += startNode.ToString();   // tack on the start node
                    distResult  = sp;                     // the distance result
                }
            }
        }
        catch (Exception ex) // typically Out Of Memory or a Command TimeOut
        {
            pathResult = ex.ToString();
            distResult = -1.0;
        }
    }
        static void Main()
        {
            /*Implement a class PriorityQueue<T> based on the data structure "binary heap".
            Write a program to read a large collection of products(name + price) and efficiently find the first 20 products in the price range[a…b].
            Test for 500 000 products and 10 000 price searches.
            Hint: you may use OrderedBag<T> and sub-ranges.
            Write a program that finds a set of words (e.g. 1000 words) in a large text(e.g. 100 MB text file).
            Print how many times each word occurs in the text.
            Hint: you may find a C# trie in Internet.*/
            var priorityQueue = new MyPriorityQueue<int>();

            priorityQueue.Enqueue(1);
            priorityQueue.Enqueue(3);
            priorityQueue.Enqueue(18);
            priorityQueue.Enqueue(4);
            priorityQueue.Enqueue(105);
            priorityQueue.Enqueue(213);

            var last = priorityQueue.Dequeue();

            Console.WriteLine("TASK 1:");
            Console.WriteLine("Dequed: " + last);
            Console.WriteLine("Size of queue: " + priorityQueue.Count());
            Console.WriteLine("All elements: \n" + String.Join(", ", priorityQueue.All()));
            Console.WriteLine();

            /*Write a program to read a large collection of products (name + price) and efficiently find
            the first 20 products in the price range [a…b].
            Test for 500 000 products and 10 000 price searches.
            Hint: you may use OrderedBag<T> and sub-ranges.*/
            var db = new ProductsDb();

            for (int i = 0; i < 500000; i++)
            {
                db.AddProduct(new Product(GetRandomName(), GetRandomPriceInRange(0, 100000)));
            }

            Console.WriteLine("TASK 2:");
            Console.WriteLine("500 000 products added");

            var stopWatch = new Stopwatch();
            stopWatch.Start();
            var productsInRange = db.GetProductsInPriceRange(100, 3000);
            stopWatch.Stop();

            Console.WriteLine("Alll products in this range: " + productsInRange.Count);
            Console.WriteLine("Elapsed time to find all products: "+ stopWatch.Elapsed);
            Console.WriteLine();

            /*Write a program that finds a set of words(e.g. 1000 words) in a large text(e.g. 100 MB text file).
            Print how many times each word occurs in the text.
            Hint: you may find a C# trie in Internet.*/
            var sw = new Stopwatch();

            var trie = new Trie();

            for (int i = 0; i < wordsToAdd; i++)
            {
                string word = GetRandomName();
                sw.Start();
                trie.Add(word);
                sw.Stop();
            }

            Console.WriteLine("TASK 3");
            Console.WriteLine("Added {0} words for {1} time", wordsToAdd, sw.Elapsed);

            sw.Reset();
            for (int i = 0; i < wordsToSearch; i++)
            {
                string word = GetRandomName();
                sw.Start();
                trie.GetWordOccurance(word);
                sw.Stop();
            }

            Console.WriteLine("Found {0} words for {1} time", wordsToSearch, sw.Elapsed);
            Console.WriteLine("Most common word: {0}", trie.GetMostCommonWord());

        }