public static void AddProductsToBag(OrderedBag<Product> orderedBag, int numberOfItems)
 {
     for (int i = 1; i < numberOfItems; i++)
     {
         orderedBag.Add(new Product(i.ToString(), i));
     }
 }
 public ShoppingCenter()
 {
     this.byName            = new MultiDictionary <string, Product>(true);
     this.byProducer        = new MultiDictionary <string, Product>(true);
     this.byNameAndProducer = new MultiDictionary <Tuple <string, string>, Product>(true);
     this.byPrice           = new OrderedBag <Product>();
 }
    private static OrderedBag<Article> ReadArticles(string path)
    {
        OrderedBag<Article> articles = new OrderedBag<Article>();

        using (StreamReader reader = new StreamReader(path))
        {
            string line;

            while ((line = reader.ReadLine()) != null)
            {
                string[] data = line.Split('|');

                double price = double.Parse(data[0]);

                Article article = new Article(
                    price,
                    data[1].Trim(),
                    data[2].Trim(),
                    data[3].Trim());

                articles.Add(article);
            }
        }

        return articles;
    }
Example #4
0
        public static void ExecuteDijkstra(Vertex start)
        {
            OrderedBag <Vertex> pQueue = new OrderedBag <Vertex>();

            start.Cost = 0;
            pQueue.Add(start);

            while (pQueue.Count > 0)
            {
                Vertex current = pQueue.RemoveFirst();
                current.Visited = true;
                foreach (Vertex child in current.Children.Keys)
                {
                    if (!child.Visited)
                    {
                        if (child.Cost > current.Cost + current.Children[child])
                        {
                            child.Previous = current;
                            child.Cost     = current.Cost + current.Children[child];
                            pQueue.Add(child);
                        }
                    }
                }
            }
        }
Example #5
0
    static void Main()
    {
        StreamReader reader = new StreamReader(@"../../../students.txt");
        SortedDictionary<string, OrderedBag<Student>> courses = new SortedDictionary<string, OrderedBag<Student>>();
        using (reader)
        {

            string line;
            while ((line = reader.ReadLine()) != null)
            {
                string[] info = line.Split(new char[] { ' ', '|' }, StringSplitOptions.RemoveEmptyEntries);
                if (courses.ContainsKey(info[2]))
                {
                    courses[info[2]].Add(new Student(info[0], info[1]));
                }
                else
                {
                    courses[info[2]] = new OrderedBag<Student> { new Student(info[0], info[1]) };
                }
            }

            foreach (var item in courses.OrderBy(x=> x.Key))
            {
                var students = item.Value;
                Console.Write("{0}: ",item.Key);
                foreach (var student in students)
                {
                    Console.Write(student.FirstName +" "+ student.LastName+", ");
                }
                Console.WriteLine();
            }

        }
    }
        private static void SolveWithBag()
        {
            Console.WriteLine("---Bag---");
            OrderedBag<Product> bag = new OrderedBag<Product>();
            var sw = new Stopwatch();
            sw.Start();

            for (int i = 0; i < itemsCount; i++)
            {
                var price = rnd.Next(1, itemsCount);
                bag.Add(new Product(GetRandomString(), GetRandomString(), GetRandomString(), price));
            }
            Console.WriteLine("Added {0} items in {1} time", itemsCount, sw.Elapsed);

            sw.Restart();
            var secondWatch = new Stopwatch();
            for (int i = 0; i < searchesCount; i++)
            {
                var lowerProduct = new Product(GetRandomString(), GetRandomString(), GetRandomString(), rnd.Next(1, itemsCount / 2));
                var upperProduct = new Product(GetRandomString(), GetRandomString(), GetRandomString(), rnd.Next(1, itemsCount / 2));

                secondWatch.Start();
                bag.Range(lowerProduct, true, upperProduct, true);
                secondWatch.Stop();
            }
            Console.WriteLine("Found Range {0} items in {1} time", searchesCount, sw.Elapsed);
            Console.WriteLine("Actual time spent getting the Range : {0}", secondWatch.Elapsed);
        }
        public static void Main()
        {
            OrderedBag<Product> catalog = new OrderedBag<Product>();

            for (int i = 0; i < 500000; i++)
            {
                catalog.Add(new Product("Product" + i, GetRandomNumber(39,709)));
            }
            var prices = catalog.FindAll(x => x.Price > 200 && x.Price < 350);

            
            int count = 20;
            StringBuilder sb = new StringBuilder();
            foreach (var product in prices)
            {
                sb.AppendFormat("name: {0} -> price {1}", product.Name, product.Price);
                sb.AppendLine();
               
                count -= 1;
                if (count <= 0)
                {
                    break;
               }
            }
            Console.WriteLine("Print results: ");
            Console.WriteLine(sb.ToString());
        }
        public static void Main()
        {
            var collectionOfProducts = new OrderedBag<Product>();

            for (int i = 0; i < NumberOfProducts; i++)
            {
                var product = new Product(RandomGenerator.GetRandomStringWithRandomLength(3, 7),
                    RandomGenerator.RandomDecimalBetween(1, 100));
                collectionOfProducts.Add(product);
            }

            Console.WriteLine("{0} products have been generated!", NumberOfProducts);

            var testSearch = new List<Product>();

            Console.WriteLine("Running {0} searches:", NumberOfSearches);
            for (int i = 0; i < NumberOfSearches; i++)
            {
                testSearch = SearchProductsByRange(collectionOfProducts, RandomGenerator.RandomDecimalBetween(1, 10),
                    RandomGenerator.RandomDecimalBetween(11, 100));

                if (i%100 == 0)
                {
                    Console.Write("=");
                }
            }

            Console.WriteLine("\r\nTotal products matching the last search criteria: {0}", testSearch.Count);
            Console.WriteLine("First 20 products:");
            foreach (var product in testSearch.Take(20))
            {
                Console.WriteLine(product);
            }
        }
    /// <summary>
    /// Deletes product from the collection by producer
    /// </summary>
    /// <param name="producer">product producer</param>
    /// <returns>number of deleted items</returns>
    public int DeleteByProducer(string producer)
    {
        if (!this.byProducer.ContainsKey(producer))
        {
            return(0);
        }

        OrderedBag <Product> productsToDelete = this.byProducer[producer];

        this.byProducer.Remove(producer);

        foreach (Product product in productsToDelete)
        {
            this.byName[product.Name].Remove(product);
            if (byName[product.Name].Count == 0)
            {
                byName.Remove(product.Name);
            }

            this.byNameAndProducer[product.Name + product.Producer].Remove(product);
            if (byNameAndProducer[product.Name + product.Producer].Count == 0)
            {
                byNameAndProducer.Remove(product.Name + product.Producer);
            }

            this.byPrice[product.Price].Remove(product);
            if (byPrice[product.Price].Count == 0)
            {
                byPrice.Remove(product.Price);
            }
        }

        return(productsToDelete.Count);
    }
        static void DijkstraAlgorithm(Node[] graph, Node source)
        {
            var priority = new OrderedBag<Node>();

            for (int i = 1; i < graph.Length; i++)
            {
                graph[i].DijkstraDistance = int.MaxValue;
            }

            source.DijkstraDistance = 0;
            priority.Add(source);

            while (priority.Count != 0)
            {
                Node currentNode = priority.RemoveFirst();

                if (currentNode.DijkstraDistance == int.MaxValue)
                {
                    break;
                }

                for (int i = 0; i < currentNode.Edges.Count; i++)
                {
                    int potDistance = currentNode.DijkstraDistance + currentNode.Edges[i].Weight;

                    if (potDistance < graph[currentNode.Edges[i].NodeId].DijkstraDistance)
                    {
                        graph[currentNode.Edges[i].NodeId].DijkstraDistance = potDistance;
                        priority.Add(graph[currentNode.Edges[i].NodeId]);
                    }
                }
            }
        }
    static void Main()
    {
        StringBuilder allProductsToString = new StringBuilder();
            Stopwatch stopWatch = new Stopwatch();
            OrderedBag<Product> siabongaOrderedBag = new OrderedBag<Product>();
            int ranges = 10000;

            //stopWatch.Start();
            AddProductsToBag(siabongaOrderedBag, 500001);

            List<Product> twentyProductsInSomeRange=FindFirstTwenty(siabongaOrderedBag,55,452);
            for (int i = 0; i<twentyProductsInSomeRange.Count; i++)
            {
                Console.WriteLine("Name: "+twentyProductsInSomeRange[i].Name+"  Price: "+twentyProductsInSomeRange[i].Price);
            }

                stopWatch.Start();
            for (int i = 0; i < ranges; i++)
            {
                //stopWatch.Start();
                List<Product> found = FindFirstTwenty(siabongaOrderedBag, 100000, 100000 + i);

                //time for adding to stringbuilder not included
                //stopWatch.Stop();
                allProductsToString.Append(found.GetProductsToString());
            }

            // uncomment to see all ranges found
            // Console.WriteLine(allProductsToString.ToString());
            Console.WriteLine("Range searching of first 20 elm. in 500 000 elm. 10 000 times done for:\n                            "
                                + stopWatch.Elapsed);
    }
Example #12
0
        public static void Main()
        {
            string[] stringValues = new string[500000];
            for (int i = 0; i < 500000; i++)
            {
                stringValues[i] = RandomString(5);
            }

            decimal[] numberValues = new decimal[500000];
            for (int i = 0; i < 500000; i++)
            {
                numberValues[i] = GetRandomNumber(1, 1000);
            }

            OrderedBag<Product> products = new OrderedBag<Product>();

            for (int i = 0; i < 500000; i++)
            {
                products.Add(new Product
                {
                    Name = stringValues[i],
                    Price = numberValues[i]
                });
            }

            Console.WriteLine("Products added!");

            TestOrderBagSearchSpeed(products);
        }
        public static void Main()
        {
            OrderedBag<Product> products = new OrderedBag<Product>();

            for (int i = 0; i < 500000; i++)
            {
                var newProduct = new Product()
                {
                    Name = string.Format("Product #{0}", i + 1),
                    Price = Math.Round((decimal)(random.NextDouble() * 10000), 2)
                };

                products.Add(newProduct);
            }


            var priceFrom = 999;
            var PriceTo = 1000;
            Console.WriteLine("Sub-range [{0}...{1}]: ", priceFrom, PriceTo);
            var result = products.Range(new Product() { Price = priceFrom }, true, new Product() { Price = PriceTo}, true);

            foreach(var product in result)
            {
                Console.WriteLine(product);
            }
        }
Example #14
0
        private static void PrintFirst20ProductsInRange(OrderedBag<Product> products)
        {
            // find first 20 elements in range
            var lowAndHighBound = GenerateBoundToSearchTo();

            var productsInRange = products.Range(new Product(lowAndHighBound[0], "low"), true, new Product(lowAndHighBound[1], "high"), true);

            Console.WriteLine("Start searching from: {0}", lowAndHighBound[0]);
            Console.WriteLine("End searching to: {0}", lowAndHighBound[1]);

            if (productsInRange.Count >= 20)
            {
                for (int i = 0; i < 20; i++)
                {
                    Console.WriteLine(productsInRange[i]);
                }
            }
            else
            {
                foreach (var product in productsInRange)
                {
                    Console.WriteLine(product);
                }
            }
        }
Example #15
0
 private static void InitializeDataStructures()
 {
     edges         = new List <Edge>();
     d             = new int[nodesCount];
     d             = d.Select(e => e = int.MaxValue).ToArray();
     priorityQueue = new OrderedBag <int>(Comparer <int> .Create((first, second) => d[first] - d[second]));
 }
Example #16
0
        private static List <Edge> Prim(int node)
        {
            List <Edge> spanningTree = new List <Edge>();

            spanningTreeNodes.Add(node);
            OrderedBag <Edge> prioriryQueue = new OrderedBag <Edge>(nodesByEdges[node]);

            while (prioriryQueue.Count > 0)
            {
                Edge edge = prioriryQueue.GetFirst();
                prioriryQueue.RemoveFirst();
                int nextNode = -1;

                if (spanningTreeNodes.Contains(edge.StartNode) && !spanningTreeNodes.Contains(edge.EndNode))
                {
                    nextNode = edge.EndNode;
                }

                if (spanningTreeNodes.Contains(edge.EndNode) && !spanningTreeNodes.Contains(edge.StartNode))
                {
                    nextNode = edge.StartNode;
                }

                if (nextNode == -1)
                {
                    continue;
                }

                spanningTree.Add(edge);
                spanningTreeNodes.Add(nextNode);
                prioriryQueue.AddMany(nodesByEdges[nextNode]);
            }

            return(spanningTree);
        }
Example #17
0
        static void Main(string[] args)
        {
            OrderedBag <Product> products = new OrderedBag <Product>();

            Random random = new Random();

            for (int i = 0; i < 50000; i++)
            {
                products.Add(new Product("item" + i, random.Next(0, int.MaxValue)));
            }

            var prices = products.FindAll(x => x.Price > 0);

            for (int i = 0; i < 10000; i++)
            {
                int min = random.Next(0, int.MaxValue);
                int max = random.Next(min, int.MaxValue);
                prices = products.FindAll(x => x.Price > min && x.Price < max);
            }

            int counter = 20;

            foreach (var item in prices)
            {
                if (counter != 0)
                {
                    Console.WriteLine("Name: {0} Price: {1}", item.Name, item.Price);
                    counter--;
                }
            }
        }
Example #18
0
    public static void Main()
    {
        OrderedBag<Product> test = new OrderedBag<Product>();
        string originalName = "Product";
        decimal originalPrice = 1;
        Product productToAdd;

        for (int i = 0; i < 500000; i++)
        {
            productToAdd = new Product(originalName + i, originalPrice + i);
            test.Add(productToAdd);
        }

        int numberOfRangeChecks = 0;
        List<Product> topTwentyProductsInRange = new List<Product>();

        for (int i = 0, j = 10000; i < 10000; i++, j += 10)
        {
            var productsInRange = test.Range(new Product("", i), true, new Product("", j), true);

            for (int k = 0; k < 20; k++)
			{
                topTwentyProductsInRange.Add(productsInRange[k]);
			}

            numberOfRangeChecks++;
        }
    }
Example #19
0
        private static Dictionary <int, int> Prim(int startNode)
        {
            // node -> depth
            var tree = new Dictionary <int, int>
            {
                { startNode, 1 }
            };

            var queue = new OrderedBag <Edge>(
                Comparer <Edge> .Create((f, s) => f.Distance - s.Distance));

            queue.AddMany(graph[startNode]);

            while (queue.Count > 0)
            {
                var edge = queue.RemoveFirst();

                var nonTreeNode = GetNonTreeNode(tree, edge);

                if (nonTreeNode == -1)
                {
                    continue;
                }

                var treeNode = GetTreeNode(tree, edge);

                // node -> depth
                tree.Add(nonTreeNode, tree[treeNode] + 1);

                queue.AddMany(graph[nonTreeNode]);
            }

            return(tree);
        }
Example #20
0
        private static void RandomSearch(OrderedBag <Product> products, int count, bool toShowInConsole)
        {
            var firstRandomPriceProduct  = new Product("", random.GenerateRandomNumber(1, 1000000));
            var secondRandomPriceProduct = new Product("", random.GenerateRandomNumber(1000000, 2000000));

            Console.Write("Searching {0} times", count);
            for (int i = 0; i < count; i++)
            {
                if (i % 500 == 0)
                {
                    Console.Write(".");
                }
                var findedProducts = products.Range(firstRandomPriceProduct, true, secondRandomPriceProduct, true).Take(20);
                firstRandomPriceProduct.Price  = random.GenerateRandomNumber(1, 1000000);
                secondRandomPriceProduct.Price = random.GenerateRandomNumber(1000000, 2000000);

                //    if (toShowInConsole)
                //    {
                //        foreach (var product in findedProducts)
                //        {
                //            Console.WriteLine(product.Name + " " + product.Price);
                //        }
                //    }
            }
        }
Example #21
0
        public static void Main()
        {
            coursesStudents = new SortedDictionary <string, OrderedBag <Student> >();
            using (StreamReader reader = new StreamReader("..\\..\\students.txt"))
            {
                while (!reader.EndOfStream)
                {
                    string[] lineElements = reader.ReadLine().Split('|').Select(x => x.Trim()).ToArray();
                    string   courseKey    = lineElements[2];

                    if (!coursesStudents.ContainsKey(courseKey))
                    {
                        var orderedBag = new OrderedBag <Student>(new Student());
                        coursesStudents.Add(courseKey, orderedBag);
                    }

                    coursesStudents[courseKey].Add(new Student
                    {
                        Name   = lineElements[0],
                        Family = lineElements[1]
                    });
                }
            }

            Print();
        }
Example #22
0
        public static IEnumerable <T> Sort(IEnumerable <OrderedBag <T> > remotes)
        {
            OrderedBag <Tuple <T, OrderedBag <T> > > buffer =
                new OrderedBag <Tuple <T, OrderedBag <T> > >((a, b) => a.Item1.CompareTo(b.Item1));

            // Initialize heap.
            foreach (var remote in remotes)
            {
                if (remote.Count > 0)
                {
                    T elem = remote.RemoveFirst();
                    buffer.Add(new Tuple <T, OrderedBag <T> >(elem, remote));
                }
            }

            // Retrieve min element on each step.
            while (buffer.Count > 0)
            {
                Tuple <T, OrderedBag <T> > nextMin = buffer.RemoveFirst();
                yield return(nextMin.Item1);

                if (nextMin.Item2.Count > 0)
                {
                    buffer.Add(
                        new Tuple <T, OrderedBag <T> >(
                            nextMin.Item2.RemoveFirst(),
                            nextMin.Item2));
                }
            }
        }
        public static void Main()
        {
            var products = new OrderedBag<Product>();
            var builder = new StringBuilder();
            int n = int.Parse(Console.ReadLine());

            for (int i = 0; i < n; i++)
            {
                var productPriceTokens = Console.ReadLine().Split();
                var name = productPriceTokens[0];
                var price = float.Parse(productPriceTokens[1]);

                products.Add(new Product(name, price));
            }

            var pricesTokens = Console.ReadLine().Split();
            var lower = float.Parse(pricesTokens[0]);
            var upper = float.Parse(pricesTokens[1]);

            var subrangeProducts = products.Range(new Product(string.Empty, lower), true, new Product(string.Empty, upper), true);

            foreach (var product in subrangeProducts)
            {
                Console.WriteLine(product.ToString());
            }
        }
Example #24
0
        public static void Main(string[] args)
        {
            OrderedBag<Product> products = new OrderedBag<Product>();
            Random randomNumberGenerator = new Random();
            double randomNumber;
            for (int i = 0; i < 500000; i++)
            {
                randomNumber = randomNumberGenerator.NextDouble() * MaxValue;
                Product product = new Product("product" + i, randomNumber);
                products.Add(product);
            }

            double from;
            double to;
            for (int i = 0; i < 10000; i++)
            {
                from = randomNumberGenerator.NextDouble() * MaxValue;
                to = randomNumberGenerator.NextDouble() * MaxValue;
                var productInRange = products.Range(new Product("searchFrom", from), true, new Product("searchTo", to), true);
                foreach (var item in productInRange.Take(20))
                {
                    Console.Write("[{0} => {1}] ", item.Name, Math.Round(item.Price, 2));
                }

                Console.WriteLine();
            }
        }
Example #25
0
        static void Main()
        {
            OrderedBag<Product> products = new OrderedBag<Product>();

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            for (int i = 1; i < 500000; i++)
            {
                Product p = new Product();
                p.Name = "Prodcut" + i;
                p.Price = GetRandomNumber(35, 599) * i * GetRandomNumber(3, 5) / GetRandomNumber(2, 4);
                products.Add(p);
            }

            stopwatch.Stop();
            Console.WriteLine("Create and Add 500k products: {0}", stopwatch.Elapsed);

            List<Product> prodRange = new List<Product>();
            stopwatch.Reset();
            stopwatch.Restart();

            for (int i = 1; i <= 10000; i++)
            {
                int min = GetRandomNumber(35, 599) * i * GetRandomNumber(3, 5) / GetRandomNumber(2, 4);
                int max = GetRandomNumber(35, 599) * i * 13 * GetRandomNumber(3, 5);

                prodRange.AddRange(products.Range(new Product() { Price = min }, true, new Product() { Price = max }, true).Take(20));
            }

            stopwatch.Stop();
            Console.WriteLine("Search for 10k random price ranges: {0}", stopwatch.Elapsed);
        }
Example #26
0
        private static void PrintFirst20ProductsInRange(OrderedBag <Product> products)
        {
            // find first 20 elements in range
            var lowAndHighBound = GenerateBoundToSearchTo();

            var productsInRange = products.Range(new Product(lowAndHighBound[0], "low"), true, new Product(lowAndHighBound[1], "high"), true);

            Console.WriteLine("Start searching from: {0}", lowAndHighBound[0]);
            Console.WriteLine("End searching to: {0}", lowAndHighBound[1]);

            if (productsInRange.Count >= 20)
            {
                for (int i = 0; i < 20; i++)
                {
                    Console.WriteLine(productsInRange[i]);
                }
            }
            else
            {
                foreach (var product in productsInRange)
                {
                    Console.WriteLine(product);
                }
            }
        }
        public static void Main(string[] args)
        {
            string input = string.Empty;
            var    list  = new OrderedBag <int>();

            while ((input = Console.ReadLine()) != "EXIT")
            {
                var splitInput = input.Split().ToArray();
                if (splitInput[0] == "ADD")
                {
                    list.Add(int.Parse(splitInput[1]));
                }

                else
                {
                    double median;
                    if (list.Count % 2 == 0)
                    {
                        median = (double)(list[list.Count / 2] + list[list.Count / 2 - 1]) / 2;
                    }
                    else
                    {
                        median = (double)list[list.Count / 2];
                    }
                    Console.WriteLine(median);
                }
            }
        }
Example #28
0
        static void DijkstraAlgorithm(Node[] graph, Node source)
        {
            var priority = new OrderedBag <Node>();

            for (int i = 1; i < graph.Length; i++)
            {
                graph[i].DijkstraDistance = int.MaxValue;
            }

            source.DijkstraDistance = 0;
            priority.Add(source);

            while (priority.Count != 0)
            {
                Node currentNode = priority.RemoveFirst();

                if (currentNode.DijkstraDistance == int.MaxValue)
                {
                    break;
                }

                for (int i = 0; i < currentNode.Edges.Count; i++)
                {
                    int potDistance = currentNode.DijkstraDistance + currentNode.Edges[i].Weight;

                    if (potDistance < graph[currentNode.Edges[i].NodeId].DijkstraDistance)
                    {
                        graph[currentNode.Edges[i].NodeId].DijkstraDistance = potDistance;
                        priority.Add(graph[currentNode.Edges[i].NodeId]);
                    }
                }
            }
        }
        public static void Main(string[] args)
        {
            StreamReader reader = new StreamReader(@"..\..\students.txt");
            using (reader)
            {
                SortedDictionary<string, OrderedBag<Student>> students = new SortedDictionary<string, OrderedBag<Student>>();
                for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
                {
                    var input = line.Split('|');
                    if (!students.ContainsKey(input[2].Trim()))
                    {
                        var grouped = new OrderedBag<Student>();
                        grouped.Add(new Student(input[0].Trim(), input[1].Trim()));
                        students.Add(input[2].Trim(), grouped);
                    }
                    else
                    {
                        students[input[2].Trim()].Add(new Student(input[0].Trim(), input[1].Trim()));
                    }
                }

                foreach (var student in students)
                {
                    Console.WriteLine(student);
                }
            }
        }
    static void Main()
    {
        Console.WriteLine("Generating product's list...");
        var produkts = new OrderedBag<Product>();
        Random rnd = new Random();
        for (int i = 0; i < 500000; i++)
        {
            int price = rnd.Next(1, 100001);
            string name = "product-" + i;
            Product product = new Product(name, price);
            produkts.Add(product);
        }

        Console.WriteLine("Searching 20 products in range 10257 - 11336 lv");
        Predicate<Product> isProduktInRange = p => p.Price >= 10257 && p.Price <= 11336;
        var range = produkts.FindAll(isProduktInRange);
        int count = 0;
        foreach (var item in range)
        {
            Console.WriteLine(item);
            ++count;
            if (count == 20)
            {
                return;
            }
        }
    }
Example #31
0
        private static void Prim()
        {
            var queue = new OrderedBag <Edge>
                            (Comparer <Edge> .Create((f, s) => f.Weight - s.Weight));

            foreach (var node in forest)
            {
                queue.AddMany(graph[node]);
            }
            while (queue.Count > 0)
            {
                var edge = queue.RemoveFirst();
                if (leftBudget - edge.Weight < 0)
                {
                    break;
                }

                var nonTreeNode = FindNonTreeNode
                                      (edge.First, edge.Second);
                if (nonTreeNode != -1)
                {
                    forest.Add(nonTreeNode);
                    leftBudget -= edge.Weight;
                    queue.AddMany(graph[nonTreeNode]);
                }
            }
        }
        static void Main()
        {
            var collection = new OrderedBag<Product>();
            int numberOfProducts = 500000;
            int numberOfProductsToTake = 10000;

            Console.WriteLine("Products generation started");
            for (var i = 0; i < numberOfProducts; i++)
            {
                var product = new Product("Product #" + i, (decimal)i);
                collection.Add(product);
            }
            Console.WriteLine("Products generated");

            var stringBuilder = new StringBuilder();

            Console.WriteLine("Collecting products...");
            for (var i = 0; i < numberOfProductsToTake; i++)
            {
                var rangeOfProducts =
                    collection.Range(new Product("StartSearchProduct", 154000m), true, new Product("EndSearchProduct", 155000m), true)
                        .Take(20);
                stringBuilder.AppendLine(string.Join(", ", rangeOfProducts.Select(p => p.ToString())));
            }

            Console.WriteLine(stringBuilder.ToString());
        }
Example #33
0
        private static void AddProduct(string name, string producer, string stringPrice)
        {
            var price = decimal.Parse(stringPrice);
            var currentProduct = new Product(name, producer, price);

            if (!productsByName.ContainsKey(name))
            {
                productsByName[name] = new OrderedBag<Product>();
            }
            productsByName[name].Add(currentProduct);

            if (!productsByProducer.ContainsKey(producer))
            {
                productsByProducer[producer] = new OrderedBag<Product>();
            }
            productsByProducer[producer].Add(currentProduct);

            if (!productsByPrice.ContainsKey(price))
            {
                productsByPrice[price] = new OrderedBag<Product>();
            }
            productsByPrice[price].Add(currentProduct);

            Console.WriteLine(AddedMessage);
        }
    internal static void Main()
    {
        var myStore = new OrderedBag<Product>();
        var ran = new Random();
        for (int i = 0; i < 500000; i++)
        {
            myStore.Add(new Product("prod." + ran.Next(1, 500001), ran.Next(1, 10011) / 100m));
        }

        var result = new StringBuilder();
        for (int i = 0; i < 10000; i++)
        {
            var prodList = myStore.Range(new Product(string.Empty, i + 1), true, new Product(string.Empty, i + 2), true);
            var counter = 0;
            foreach (var item in prodList)
            {
                if (counter == 20)
                {
                    break;
                }

                result.AppendFormat("{3}. Product: {0} Price: {1} BGN {2}", item.Name, item.Price, Environment.NewLine, counter + 1);
                counter++;
            }
        }

        Console.WriteLine(result);
    }
Example #35
0
        /// <summary>
        /// OrderedBag<T>
        /// A bag (multi-set) based on balanced search tree (WITH DUPLICATES)
        /// Add / Find / Remove work in time O(log(N))
        /// T should implement IComparable<T>
        /// </summary>
        private static void TestOrderedBag()
        {
            OrderedBag <Student> orderedBagOfStudents = new OrderedBag <Student>();
            var student1 = new Student("Pesho", 21);
            var student2 = new Student("Pesho", 21);

            orderedBagOfStudents.Add(student1);
            orderedBagOfStudents.Add(student2);
            Console.WriteLine("Equals: " + student1.Equals(student2));
            Console.WriteLine("CompareTo: " + student1.CompareTo(student2));
            Console.WriteLine(student1.GetHashCode());
            Console.WriteLine(student2.GetHashCode());
            orderedBagOfStudents.Add(student1);
            var student3 = new Student("Pesho", 22);
            var student4 = new Student("Pesho", 23);
            var student5 = new Student("Pesho", 24);

            orderedBagOfStudents.Add(student3);
            orderedBagOfStudents.Add(student4);
            orderedBagOfStudents.Add(student5);
            foreach (var item in orderedBagOfStudents)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("========== Range Age >= 22 && <= 23 ============= ");
            var rangeBag = orderedBagOfStudents.Range(student3, true, student4, true);

            foreach (var item in rangeBag)
            {
                Console.WriteLine(item);
            }
        }
        public static SortedDictionary<string, OrderedBag<Student>> ReadStudents(string path)
        {
            var result = new SortedDictionary<string, OrderedBag<Student>>();

            using (var reader = new StreamReader("students.txt"))
            {
                var currentLine = reader.ReadLine();

                while (currentLine != null)
                {
                    var tokens = currentLine.Split(new char[] { ' ', '|', }, StringSplitOptions.RemoveEmptyEntries);
                    var course = tokens[2].Trim();
                    Student student = new Student(tokens[0].Trim(), tokens[1].Trim(), course);
                    
                    if (result.ContainsKey(course))
                    {
                        result[course].Add(student);
                    }
                    else
                    {
                        result[course] = new OrderedBag<Student>();
                        result[course].Add(student);
                    }

                    currentLine = reader.ReadLine();
                }

                return result;
            }


           // return result;
        }
Example #37
0
        public static void Main()
        {
            myWatch.Start();
            
            Random randomGen = new Random();
            OrderedBag<Product> myBag = new OrderedBag<Product>();

            for (int i = 0; i < 500000; i++)
            {
                myBag.Add(new Product("Product" + i, randomGen.Next(1, 1000000)));
            }

            int start = 0;
            int end = 1000;
            for (int i = 0; i < 10000; i++)
            {
                var subBag = myBag.Range(new Product(string.Empty, start), true, new Product(string.Empty, end), true);
                IList<Product> firstTwenty = GetFirstResults(subBag);

                ////Console.WriteLine("Results");
                ////foreach (Product product in firstTwenty)
                ////{
                ////    Console.WriteLine(product);
                ////}

                start += 10;
                end += 10;
            }

            myWatch.Stop();
            Console.WriteLine("END");
            Console.WriteLine("Time: {0}", myWatch.Elapsed);
        }
Example #38
0
        public static void Main()
        {
            OrderedBag<Product> orderedBag = new OrderedBag<Product>();

            AddProducts(orderedBag);
            FindProductsInPriceRange(orderedBag);
        }
Example #39
0
        public void ListEvents(DateTime date, int count)
        {
            OrderedBag <Event> .View eventsToShow = this.orderedByDate.RangeFrom(
                new Event(date, string.Empty, string.Empty),
                true);

            int showed = 0;

            foreach (var eventToShow in eventsToShow)
            {
                if (showed == count)
                {
                    break;
                }

                Messages.PrintEvent(eventToShow);

                showed++;
            }

            if (showed == 0)
            {
                Messages.NoEventsFound();
            }
        }
Example #40
0
 private static void AddProducts(OrderedBag<Product> orderedBag)
 {
     for (int i = 0; i < ProductsCount; i++)
     {
         orderedBag.Add(new Product("Product " + (i + 1), GetRandomNumber(10, 17500) + (decimal)i / 100));
     }
 }
    public static IEnumerable <T> Merge <T>(
        IEnumerable <IEnumerable <T> > listOfLists,
        Func <T, T, int> comparison = null)
    {
        IComparer <T> cmp = comparison != null
                                ? Comparer <T> .Create(new Comparison <T>(comparison))
                                : Comparer <T> .Default;

        List <IEnumerator <T> > es = listOfLists
                                     .Select(l => l.GetEnumerator())
                                     .Where(e => e.MoveNext())
                                     .ToList();
        var bag = new OrderedBag <KeyEnumerator <T> >();

        es.ForEach(e => bag.Add(new KeyEnumerator <T>(e.Current, e, cmp)));
        while (bag.Count > 0)
        {
            KeyEnumerator <T> kv = bag.RemoveFirst();
            IEnumerator <T>   e  = kv.Enumerator;
            yield return(e.Current);

            if (e.MoveNext())
            {
                bag.Add(new KeyEnumerator <T>(e.Current, e, cmp));
            }
        }
    }
Example #42
0
        static void Main(string[] args)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            string path = "..\\..\\Products.txt";
            OrderedBag <Product> productsCollection = new OrderedBag <Product>();
            Stopwatch            sw = new Stopwatch();
            double minPrice         = 10;
            double maxPrice         = 10000;

            Console.WriteLine("Reading products file...");
            productsCollection = ReadProductsFile(path);
            Console.WriteLine();

            Console.WriteLine("Searching 10000 times for products...");

            sw.Start();
            for (int i = 0; i < 10000; i++)
            {
                SearchProducts(productsCollection, minPrice + i, maxPrice + i);
            }
            sw.Stop();

            Console.Write("Done in:");
            Console.WriteLine(sw.Elapsed);
        }
        private static Product[] First20ProductsInInterval(decimal minPrice, decimal maxPrice, OrderedBag<Product> products)
        {
            if (minPrice > maxPrice)
            {
                throw new ArgumentException("Maximal price must be greater or equal than minimal price!");
            }

            GenerateExceptionIfValueLessThanZero(minPrice, "minPrice");
            GenerateExceptionIfValueLessThanZero(maxPrice, "maxPrice");

            OrderedBag<Product>.View productsInRange =
                products.Range(
                new Product("testerMin", minPrice),
                true,
                new Product("testerMin", maxPrice),
                true);

            if (productsInRange.Count == 0) 
            {
                return new Product[0];
            }

            int selectedItemsLen = (20 > productsInRange.Count) ? productsInRange.Count : 20;  
            Product[] selectedItems = new Product[selectedItemsLen];

            for (int i = 0; i < selectedItemsLen; i++)
            {
                selectedItems[i] = productsInRange[i];
            }

            return selectedItems;
        }
Example #44
0
        public int Part2()
        {
            var meObjectOrbit    = _map.First(x => x.Name == "YOU").OrbitsOn;
            var santaOrbitObject = _map.First(x => x.Name == "SAN").OrbitsOn;

            var vertexes = new OrderedBag <Vertex>();

            foreach (var oribitngObject in _map.Where(x => x.Name != "YOU" && x.Name != "SAN"))
            {
                vertexes.Add(new Vertex(oribitngObject, oribitngObject.Equals(meObjectOrbit) ? 0 : int.MaxValue));
            }

            while (vertexes.Any())
            {
                var u          = vertexes.RemoveFirst();
                var neighbours = vertexes.Where(x =>
                                                (x.OribitngObject.OrbitsOn.Equals(u.OribitngObject) || x.OribitngObject.Equals(u.OribitngObject.OrbitsOn)) && u.Cost + 1 < x.Cost).ToList();

                if (u.OribitngObject.Equals(santaOrbitObject))
                {
                    return(u.Cost);
                }

                foreach (var neighbour in neighbours.Where(neighbour => u.Cost + 1 < neighbour.Cost))
                {
                    neighbour.Cost = u.Cost + 1;
                }

                vertexes = new OrderedBag <Vertex>(vertexes);
            }

            return(-1);
        }
Example #45
0
        public static void Dijkstra(Vertex start)
        {
            var q = new OrderedBag <Vertex>(); // use priority q

            start.Cost = 0;
            q.Add(start);

            while (q.Count > 0)
            {
                var current = q.RemoveFirst();
                current.Visited = true;

                foreach (var child in current.Children.Keys)
                {
                    if (!child.Visited)
                    {
                        if (child.Cost > current.Cost + current.Children[child])
                        {
                            child.Cost     = current.Cost + current.Children[child];
                            child.Previous = current;
                            q.Add(child);
                        }
                    }
                }
            }
        }
Example #46
0
        private static void FillTheKnapsack(OrderedBag<PriceWeigth> priceWeigth, int maxCapacity)
        {
            double totalPrice = 0;

            int lastItemIndex = 0;
            var priceWeigthList = priceWeigth.Reversed().ToList();

            int currentLoad = 0;
            while (currentLoad < maxCapacity)
            {
                int crntItemWeight = priceWeigthList[lastItemIndex].Weight;
                if (currentLoad + crntItemWeight <= maxCapacity)
                {
                    totalPrice += priceWeigthList[lastItemIndex].Price;
                    lastItemIndex++;
                    currentLoad += crntItemWeight;
                }
                else
                {
                    double pricePortion = (maxCapacity - currentLoad) / (double)crntItemWeight;
                    totalPrice += (priceWeigthList[lastItemIndex].Price * pricePortion);
                    currentLoad += crntItemWeight;
                }
            }

            Console.WriteLine("Total price = {0:f2}", totalPrice);
        }
Example #47
0
 public static void AddProductsToBag(OrderedBag <Product> orderedBag, int numberOfItems)
 {
     for (int i = 1; i < numberOfItems; i++)
     {
         orderedBag.Add(new Product(i.ToString(), i));
     }
 }
Example #48
0
    static void Main()
    {
        StreamReader reader = new StreamReader(@"../../../students.txt");
        SortedDictionary <string, OrderedBag <Student> > courses = new SortedDictionary <string, OrderedBag <Student> >();

        using (reader)
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                string[] info = line.Split(new char[] { ' ', '|' }, StringSplitOptions.RemoveEmptyEntries);
                if (courses.ContainsKey(info[2]))
                {
                    courses[info[2]].Add(new Student(info[0], info[1]));
                }
                else
                {
                    courses[info[2]] = new OrderedBag <Student> {
                        new Student(info[0], info[1])
                    };
                }
            }

            foreach (var item in courses.OrderBy(x => x.Key))
            {
                var students = item.Value;
                Console.Write("{0}: ", item.Key);
                foreach (var student in students)
                {
                    Console.Write(student.FirstName + " " + student.LastName + ", ");
                }
                Console.WriteLine();
            }
        }
    }
        static void DijkstraFindMinCableLengthBetweenHouses(Dictionary<HouseNode, 
            List<CableConnection>> graph, HouseNode houseToStartFrom)
        {
            OrderedBag<HouseNode> houseQueue = new OrderedBag<HouseNode>();

            foreach (var house in graph)
            {
                house.Key.MinCableLenth = int.MaxValue;
            }

            houseToStartFrom.MinCableLenth = 0;
            houseQueue.Add(houseToStartFrom);

            while (houseQueue.Count > 0)
            {
                var currentHouse = houseQueue.RemoveFirst();

                if (currentHouse.MinCableLenth == int.MaxValue)
                {
                    break;
                }

                foreach (var connection in graph[currentHouse])
                {
                    var currentCableLength = currentHouse.MinCableLenth + connection.CableLenth;
                    if (connection.House.MinCableLenth > currentCableLength)
                    {
                        connection.House.MinCableLenth = currentCableLength;
                        houseQueue.Add(connection.House);
                    }
                }
            }
        }
        private static void DijkstraAlgorithm()
        {
            while (queue.Count != 0)
            {
                var minNode       = queue.RemoveFirst();
                var childrenEdges = edges.Where(e => e.first == minNode || e.second == minNode).ToArray();
                if (d[minNode] == int.MaxValue)
                {
                    break;
                }
                foreach (var edge in childrenEdges)
                {
                    var child  = minNode == edge.first ? edge.second : edge.first;
                    var weight = edge.weight;
                    if (d[child] == int.MaxValue)
                    {
                        queue.Add(child);
                    }

                    int newDistance = d[minNode] + weight;
                    if (newDistance < d[child])
                    {
                        d[child]    = newDistance;
                        prev[child] = minNode;
                        queue       = new OrderedBag <int>(queue, Comparer <int> .Create((f, s) => d[f] - d[s]));
                    }
                }
            }
        }
Example #51
0
    private static IList <int> Dijkstra(int start)
    {
        var distances = Enumerable.Repeat(int.MaxValue, graph.Count).ToArray();

        var queue = new OrderedBag <Node>((node1, node2) =>
                                          node1.Distance.CompareTo(node2.Distance)
                                          );

        distances[start] = 0;
        queue.Add(new Node(start, 0));

        while (queue.Count != 0)
        {
            var currentNode = queue.RemoveFirst();

            foreach (var neighborNode in graph[currentNode.To])
            {
                int currentDistance = distances[currentNode.To] + neighborNode.Distance;

                if (currentDistance < distances[neighborNode.To])
                {
                    distances[neighborNode.To] = currentDistance;
                    queue.Add(new Node(neighborNode.To, currentDistance));
                }
            }

            // Removing repeating is actually slower?
        }

        return(distances);
    }
Example #52
0
        private static Dictionary <int, int> GetStriked(int startNode)
        {
            var striked = new Dictionary <int, int>();

            striked.Add(startNode, 1);

            var queue = new OrderedBag <Edge>(graph[startNode],
                                              Comparer <Edge> .Create((f, s) => f.Weight - s.Weight));

            while (queue.Count > 0)
            {
                var edge        = queue.RemoveFirst();
                var nonTreeNode = GetNonTreeNode(edge.First, edge.Second, striked);
                if (nonTreeNode != -1)
                {
                    var treeNode = -1;
                    if (nonTreeNode == edge.First)
                    {
                        treeNode = edge.Second;
                    }
                    else
                    {
                        treeNode = edge.First;
                    }
                    int depth = striked[treeNode];
                    striked.Add(nonTreeNode, depth + 1);
                    queue.AddMany(graph[nonTreeNode]);
                    queue = new OrderedBag <Edge>(queue,
                                                  Comparer <Edge>
                                                  .Create((f, s) => f.Weight - s.Weight));
                }
            }
            return(striked);
        }
Example #53
0
    static void Main(string[] args)
    {
        OrderedBag<Item> catalog = new OrderedBag<Item>();

        Random random = new Random();
        for (int i = 0; i < 50000; i++)
        {
            catalog.Add(new Item("item" + i, random.Next(0, int.MaxValue)));
        }
        var prices = catalog.FindAll(x => x.Price > 100 && x.Price < 150);
       
        for (int i = 0; i < 10000; i++)
        {
            int min = random.Next(0, int.MaxValue);
            int max = random.Next(min, int.MaxValue);
            prices = catalog.FindAll(x => x.Price > min && x.Price < max);
        }

        //print only the result of the last search becouse printing is very slow operation
        int count = 20;
        foreach (var item in prices)
        {
            Console.WriteLine("name:"+item.Name + "-> price:"+item.Price);
            count -= 1;
            if (count<=0)
            {
                break;
            }
        }
    }
        public static void Main(string[] args)
        {
            OrderedBag <Product> products = new OrderedBag <Product>();
            Random randomNumberGenerator  = new Random();
            double randomNumber;

            for (int i = 0; i < 500000; i++)
            {
                randomNumber = randomNumberGenerator.NextDouble() * MaxValue;
                Product product = new Product("product" + i, randomNumber);
                products.Add(product);
            }

            double from;
            double to;

            for (int i = 0; i < 10000; i++)
            {
                from = randomNumberGenerator.NextDouble() * MaxValue;
                to   = randomNumberGenerator.NextDouble() * MaxValue;
                var productInRange = products.Range(new Product("searchFrom", from), true, new Product("searchTo", to), true);
                foreach (var item in productInRange.Take(20))
                {
                    Console.Write("[{0} => {1}] ", item.Name, Math.Round(item.Price, 2));
                }

                Console.WriteLine();
            }
        }
Example #55
0
    public static void Main(string[] args)
    {
        OrderedBag <Product> productsInvetory = new OrderedBag <Product>();
        Random random = new Random();

        for (int i = 0; i < 500000; i++)
        {
            Product product = new Product("product" + i, random.Next(-i, i));
            productsInvetory.Add(product);
        }

        Console.WriteLine("Start");
        Stopwatch watch = new Stopwatch();

        watch.Start();

        for (int i = 0; i < 20000; i++)
        {
            int       startRange    = random.Next(-i, i);
            int       endRange      = random.Next(startRange, i);
            Product[] currentSearch = FindFirst20ProductsInRange(productsInvetory, startRange, endRange);
        }

        watch.Stop();
        Console.WriteLine(watch.Elapsed);
    }
 private static IEnumerable<Product> GetProductsInPriceRange(OrderedBag<Product> bag, decimal min, decimal max)
 {
     Product minProduct = bag.FirstOrDefault(p => p.Price >= min);
     Product maxProduct = bag.FirstOrDefault(p => p.Price >= max);
     var result = bag.Range(minProduct, true, maxProduct, false);
     return result.Take(20);
 }
Example #57
0
        public RasterOp Calculator(Postion startPostion)
        {
            if (!Read(startPostion.XIndex, startPostion.YIndex).HasValue)
            {
                throw new ArgumentOutOfRangeException("起始位置不含有数据");
            }
            RasterPositionValue[,] cost = new RasterPositionValue[Width, Height];
            //初始化操作
            InitializeValues(cost);
            InitializeStart(startPostion, cost);
            //使用orderbag,是的每次取出的最小值
            OrderedBag <RasterPositionValue> bag = new OrderedBag <RasterPositionValue>();

            bag.Add(cost[startPostion.XIndex, startPostion.YIndex]);
            while (bag.Count != 0)
            {
                RasterPositionValue pos = bag.RemoveFirst();
                var postions            = Sourround(cost, pos);
                foreach (var postion in postions)
                {
                    double relativeCost = Read(postion.XIndex, postion.YIndex).GetValueOrDefault() * 0.5 +
                                          Read(postion.XIndex, postion.YIndex).GetValueOrDefault() * 0.5;
                    if (pos.XIndex != postion.XIndex && pos.YIndex != postion.YIndex)
                    {
                        relativeCost *= Math.Sqrt(2);
                    }
                    cost[postion.XIndex, postion.YIndex].Visited     = true;
                    cost[postion.XIndex, postion.YIndex].HasValue    = true;
                    cost[postion.XIndex, postion.YIndex].RasterValue = (float)relativeCost
                                                                       + cost[pos.XIndex, pos.YIndex].RasterValue;
                    bag.Add(cost[postion.XIndex, postion.YIndex]);
                }
            }
            return(Result(cost));
        }
        static void Main()
        {
            OrderedBag<Product> bag = new OrderedBag<Product>();
            Random rand = new Random();
            for (int i = 0; i < CountProducts; i++)
            {
                bag.Add(GetRandomProduct(rand));
            }

            decimal minPrice = 0M;
            for (int i = 0; i < PriceSearches; i++)
            {
                Console.ForegroundColor = ConsoleColor.DarkMagenta;
                decimal maxPrice = minPrice + 100M;
                var result = GetProductsInPriceRange(bag, minPrice, maxPrice);
                Console.WriteLine(new string('$', 79));
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("First 20 Products in Price Range {0:C} - {1:C}: ", minPrice, maxPrice);
                Console.ForegroundColor = ConsoleColor.DarkYellow;
                if (result.Count() < 1) { Console.Write("None\n"); }
                Console.WriteLine(string.Join(" | ", result));
                minPrice += 100;
                Thread.Sleep(500);
            }
        }
Example #59
0
        public int Solve(int k, int[] cookies)
        {
            var bag = new OrderedBag <int>();

            foreach (var cookie in cookies)
            {
                bag.Add(cookie);
            }

            var currMinSweetCookie = bag.GetFirst();
            int steps = 0;

            while (currMinSweetCookie < k && bag.Count > 1)
            {
                var minSweetCookie       = bag.RemoveFirst();
                var beforeMinSweetCookie = bag.RemoveFirst();

                var newCookie = minSweetCookie + (2 * beforeMinSweetCookie);

                bag.Add(newCookie);

                currMinSweetCookie = bag.GetFirst();
                steps++;
            }

            return(currMinSweetCookie < k ? -1 : steps);
        }
        private static void PrintFirst20Products()
        {
            var rand = new Random();
            var orderedBag = new OrderedBag<Product>((pr, pr1) => pr.Price.CompareTo(pr1.Price));
            var start = DateTime.Now;
            for (int i = 0; i < 500000; i++)
            {
                var product = new Product
                {
                    Name = "Product" + (i + 1),
                    Price = rand.Next(1000, 50000)
                };

                orderedBag.Add(product);
            }

            for (int i = 0; i < 10000; i++)
            {
                var initialPrice = rand.Next(1000, 50000);
                var products = orderedBag.Range(new Product { Price = initialPrice }, true, new Product { Price = initialPrice + 20000 }, true).Take(20).ToList();
                foreach (var prod in products)
                {
                    Console.WriteLine("{0}->{1}", prod.Name, prod.Price);
                }
            }
            Console.WriteLine(DateTime.Now - start);
        }