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

            Random priceGenerator = new Random();
            int numberofProducts = 500000;

            for (int i = 0; i < numberofProducts; i++)
            {
                Product testProduct = new Product();
                testProduct.Price = priceGenerator.Next(1, int.MaxValue);
                testProduct.Name = "product" + i;
                products.Add(testProduct);
            }

            Console.WriteLine("{0} products added in bag.", numberofProducts);

            Product firstProduct = new Product();
            firstProduct.Price = 10;
            Product secondProduct = new Product();
            secondProduct.Price = int.MaxValue / 10;
            var productsInRange = products.Range(firstProduct, true, secondProduct, true);

            Console.WriteLine("First 20 products in range {0} - {1}", firstProduct.Price, secondProduct.Price);
            for (int i = 0; i < 20; i++)
            {
                Console.WriteLine(productsInRange[i]);
            }

            Console.WriteLine("\nProducts in range {0} - {1}", firstProduct.Price, secondProduct.Price);
            var productsInBigRange = products.Range(firstProduct, true, secondProduct, true);
            Console.WriteLine("{0} products are found.", productsInBigRange.Count);
        }
    public IEnumerable <Product> FindAllByPrice(double price)
    {
        var result = productsByPrice.Range(new Product("s", price, 0), true, new Product("j", price, 0), true);

        if (result.Any())
        {
            return(result);
        }
        return(Enumerable.Empty <Product>());
    }
Exemple #3
0
        public static void Main(string[] args)
        {
            var data = new OrderedBag <Product>();

            Console.WriteLine("Creating random products");
            for (int i = 0; i < ProductCount; i++)
            {
                data.Add(
                    new Product(
                        RandomGenerator.RandomString(RandomGenerator.RandomInt(1, 100)),
                        (double)(RandomGenerator.RandomInt(1, 100000)) / 100));
            }

            Console.WriteLine("Searching products");
            for (int i = 0; i < SearchCount; i++)
            {
                double minValue = RandomGenerator.RandomInt(1, 100);
                double maxValue = RandomGenerator.RandomInt((int)minValue, (int)minValue + 900);

                var range = data.Range(new Product("", minValue), true, new Product("", maxValue), true);
                Console.WriteLine("Search #" + i);

                for (int j = 0; j < 20; j++)
                {
                    Console.WriteLine("Item# " + j + " = " + range[j].Name);
                }
            }
        }
        private static string FindOrdersByPriceRange(string commandParametersString)
        {
            var commandParameters = commandParametersString
                                    .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                                    .ToList();

            var fromPrice = decimal.Parse(commandParameters[0]);
            var toPrice   = decimal.Parse(commandParameters[1]);

            var fromOrder = new Order {
                Price = fromPrice - 0.001m
            };
            var toOrder = new Order {
                Price = toPrice + 0.001m
            };

            var range = ordersByPrice.Range(fromOrder, false, toOrder, false);

            if (range.Count == 0)
            {
                return("No orders found");
            }

            return(string.Join(Environment.NewLine, range.OrderBy(x => x.Name)));
        }
        public static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();

            OrderedBag<Product> catalog = new OrderedBag<Product>(new Comparison<Product>((x, y) => x.Price.CompareTo(y.Price)));

            for (int i = 0; i < TotalProducts; i++)
            {
                decimal productPrice = randomGenerator.Next((int)MinProductPrice, (int)MaxProductPrice);
                string productName = "Product " + i;
                Product currentProduct = new Product(productPrice, productName);
                catalog.Add(currentProduct);
            }

            OrderedBag<Product>.View productsInRange = default(OrderedBag<Product>.View);

            for (int i = 0; i < SearchCount; i++)
            {
                productsInRange = catalog.Range(
                    new Product(MinProductRange + i * 0.001m, string.Empty), true,
                    new Product(MaxProductRange + i * 0.001m, string.Empty), true);
            }

            var firstNResults = productsInRange.Take(ResultCount);
            Console.WriteLine(string.Join(Environment.NewLine, firstNResults));

            sw.Stop();
            Console.WriteLine(sw.Elapsed);
        }
Exemple #6
0
        static void Main(string[] args)
        {
            OrderedBag <Product> products = PrepareData();
            Product lowerRange            = new Product()
            {
                Name = "Mock", Price = 0
            };
            Product hiRange = new Product()
            {
                Name = "Mock", Price = 0
            };
            Stopwatch    sw = new Stopwatch();
            StreamWriter sr = new StreamWriter("../../Results.txt");

            for (int i = 0; i < 10000; i++)
            {
                lowerRange.Price = rng.Next(0, 9999);
                hiRange.Price    = rng.Next((int)lowerRange.Price, 10001);
                sw.Restart();
                int counter = 0;
                // Enumerate through 20 products in the given range.
                foreach (var product in products.Range(lowerRange, true, hiRange, true))
                {
                    //Console.WriteLine(product);

                    if (counter++ == 20)
                    {
                        break;
                    }
                }
                sw.Stop();
                sr.WriteLine(string.Format("{3}Search in price Range({0}-{1}) - Time: {2}", lowerRange.Price, hiRange.Price, sw.Elapsed, i));
            }
            sr.Close();
        }
        static void Main(string[] args)
        {
            int items = 500010;
            int ranges = 10000;
            int priceRange = 200000;

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

            for (int i = 1; i < items; i++)
            {
                orderedBag.Add(new Product("P", i));
            }
            for (int i = 0; i < ranges; i++)
            {
                var result = orderedBag.Range(new Product("P", priceRange), true,
                    new Product("P", priceRange + 20000), true);

                if (result.Count == 0)
                {
                    Console.WriteLine("No products found.");
                }

                List<Product> collection = new List<Product>();
                for (int j = 0; j < 20 && i < result.Count; j++)
                {
                    collection.Add(result[j]);
                }

                Console.WriteLine("Collection contains {0} items. ", collection.Count);
            }
        }
        static void Main()
        {
            OrderedBag <Product> bag = new OrderedBag <Product>();
            int    productsNumber    = 500000;
            Random rand = new Random();

            for (int i = 0; i < productsNumber; i++)
            {
                bag.Add(new Product("item" + i, rand.Next(1, 100000)));
            }

            Product min = new Product("itemCompare", 17);
            Product max = new Product("itemCompare", 100);

            List <Product> itemsInRange = bag.Range(min, true, max, true).ToList();

            if (itemsInRange.Count > 20)
            {
                itemsInRange = itemsInRange.GetRange(0, 20);
            }

            foreach (var item in itemsInRange)
            {
                Console.WriteLine(" Name: " + item.Name + " Price: " + item.Price);
            }
        }
Exemple #9
0
        private static void SolveWithBag()
        {
            Console.WriteLine("-------");
            Console.WriteLine("bag:");
            Console.WriteLine();
            var sw = new Stopwatch();

            sw.Start();
            var bag = new OrderedBag <Product>();

            Console.WriteLine("Initialize time {0}", sw.Elapsed);

            sw.Restart();
            foreach (var item in arrayOfProducts)
            {
                bag.Add(item);
            }
            Console.WriteLine("Addition time {0}", sw.Elapsed);
            sw.Restart();

            var lowerProduct  = new Product("low", 150000);
            var higherProduct = new Product("high", 350000);

            for (int i = 0; i < priceCheck; i++)
            {
                bag.Range(lowerProduct, true, higherProduct, true);
            }
            Console.WriteLine("Price Checking time {0}", sw.Elapsed);
        }
Exemple #10
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);
                }
            }
        }
        /* 02. 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.
        */
        /// <summary>
        /// Mains this instance.
        /// </summary>
        public static void Main()
        {
            OrderedBag<Product> products = new OrderedBag<Product>();
            Random random = new Random();

            // Test creation and filling.
            Stopwatch watch = new Stopwatch();
            watch.Start();

            for (int i = 0; i < 500000; i++)
            {
                products.Add(new Product("Product " + i, random.Next(100, 1000)));
            }

            watch.Stop();
            Console.WriteLine("The creation of 500 000 products takes: {0}", watch.Elapsed);
            watch.Reset();

            // Test searching.
            List<Product> twentyElementsInRange = new List<Product>();

            watch.Restart();
            for (int i = 0; i < 10000; i++)
            {
                Product minSumProduct = new Product("Bulshit", random.Next(100, 500));
                Product maxSumProduct = new Product("CoolStuff", random.Next(500, 1000));
                twentyElementsInRange.AddRange(products.Range(minSumProduct, true, maxSumProduct, true).Take(20));
            }

            watch.Stop();
            Console.WriteLine("10 000 price searches takes: {0}", 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);
 }
    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++;
        }
    }
        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());
            }
        }
Exemple #15
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);
        }
        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();
            }
        }
        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());
        }
    public static void Main()
    {
        OrderedBag <Product> products = new OrderedBag <Product>();

        for (int i = 0; i < 500000; i++)
        {
            // Adding is slow
            products.Add(new Product("JustProduct" + i, (decimal)(12.234 * i + 3.234)));
        }

        Stopwatch timer = new Stopwatch();

        timer.Start();

        for (int i = 0; i < 10000; i++)
        {
            var rangeProducts = products.Range(
                new Product(string.Empty, 100m + i), true,
                new Product(string.Empty, 2000m + i * 2), true).Take(20);

            //// Print them if you want to see the result but it's slow
            //foreach (var item in rangeProducts)
            //{
            //    Console.WriteLine(item);
            //}
        }

        timer.Stop();
        Console.WriteLine(timer.Elapsed);
    }
Exemple #19
0
        public static void Main()
        {
            var productBag = new OrderedBag <Product>();

            Stopwatch timer = new Stopwatch();

            Console.Write("500,000 products additions take: ");
            timer.Start();

            for (int i = 0; i < 500000; i++)
            {
                Product randomProduct = new Product(GenerateRandomName(), GenerateRandomPrice());
                productBag.Add(randomProduct);
            }

            timer.Stop();
            Console.WriteLine(timer.Elapsed);
            timer.Reset();

            Console.Write("10,000 product searches take: ");
            timer.Start();

            for (int i = 0; i < 10000; i++)
            {
                int minPriceRange    = GenerateRandomPrice();
                int maxPriceRange    = minPriceRange + GenerateRandomPrice();
                var resultCollection = productBag.Range(new Product("", minPriceRange), true, new Product("", maxPriceRange), true).Take(20);
            }

            timer.Stop();
            Console.WriteLine(timer.Elapsed);
        }
    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);
    }
Exemple #21
0
        private static void SearchProductsInRange()
        {
            var bag   = new OrderedBag <Product>();
            var watch = new Stopwatch();

            watch.Start();
            foreach (var item in arrayOfProducts)
            {
                bag.Add(item);
            }

            Console.WriteLine("Adding Products: {0}", watch.Elapsed);
            watch.Restart();
            var bottom = new Product("bottom", PriceBotCheck);
            var top    = new Product("top", PriceTopCheck);

            for (int i = 0; i < NumberOfSearches; i++)
            {
                for (int j = 0; j < FoundProductsCount; j++)
                {
                    bag.Range(bottom, true, top, true);
                }
            }

            Console.WriteLine("{0} Price Checks with {1} elements from {2} elements in {3}", NumberOfSearches, FoundProductsCount, ProductsCount, watch.Elapsed);
            watch.Stop();
        }
        public static void Main(string[] args)
        {
            var data = new OrderedBag<Product>();

            Console.WriteLine("Creating random products");
            for (int i = 0; i < ProductCount; i++)
            {
                data.Add(
                    new Product(
                        RandomGenerator.RandomString(RandomGenerator.RandomInt(1, 100)),
                        (double)(RandomGenerator.RandomInt(1, 100000)) / 100));
            }

            Console.WriteLine("Searching products");
            for (int i = 0; i < SearchCount; i++)
            {
                double minValue = RandomGenerator.RandomInt(1, 100);
                double maxValue = RandomGenerator.RandomInt((int)minValue, (int)minValue + 900);

                var range = data.Range(new Product("", minValue), true, new Product("", maxValue), true);
                Console.WriteLine("Search #" + i);

                for (int j = 0; j < 20; j++)
                {
                    Console.WriteLine("Item# " + j + " = " + range[j].Name);
                }
            }
        }
Exemple #23
0
        static void Main(string[] args)
        {
            OrderedBag<ComparableKeyValuePair<string, int>> catalog =
                new OrderedBag<ComparableKeyValuePair<string, int>>();

            for (int i = 0; i < 25; i++)
            {
                ComparableKeyValuePair<string, int> item = new ComparableKeyValuePair<string, int>(i.ToString(), i);
                catalog.Add(item);
            }

            ComparableKeyValuePair<string, int> downRange = new ComparableKeyValuePair<string, int>("3", 3);
            ComparableKeyValuePair<string, int> upRange = new ComparableKeyValuePair<string, int>("23", 23);

            OrderedBag<ComparableKeyValuePair<string, int>>.View range = catalog.Range(downRange, true, upRange, true);
            Console.WriteLine("from 3");
            foreach (ComparableKeyValuePair<string, int> item in range)
            {
                Console.WriteLine(item.Value);
            }
            Console.WriteLine("to 23");


            // Test for 500 000 products and 10 000 price searches.

            catalog =
                new OrderedBag<ComparableKeyValuePair<string, int>>();

            Stopwatch timer = new Stopwatch();

            timer.Start();

            for (int i = 0; i <= 500000; i++)
            {
                ComparableKeyValuePair<string, int> item = new ComparableKeyValuePair<string, int>(i.ToString(), i);
                catalog.Add(item);
            }
            Console.WriteLine("Adding 500 000 elements: " + timer.Elapsed.TotalSeconds + " sec");
           

            OrderedBag<ComparableKeyValuePair<string, int>>.View bigRange = null;

            ComparableKeyValuePair<string, int> from = new ComparableKeyValuePair<string, int>("400000", 400000);
            ComparableKeyValuePair<string, int> to = new ComparableKeyValuePair<string, int>("410000", 410000);

            timer.Reset();
            timer.Start();

            for (int i = 10000; i <= 400000; i = i + 20)
            {
                bigRange = catalog.Range(from, true, to, false);

                from = new ComparableKeyValuePair<string, int>((i - 20).ToString(), (i - 20));
                to = new ComparableKeyValuePair<string, int>(i.ToString(), i);
            }

            Console.WriteLine("10 000 searches (200 000 to 400 000):" + timer.Elapsed.TotalMilliseconds + " ms");

            timer.Stop();
        }
        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);
            }
        }
Exemple #25
0
        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);
        }
    static void Main()
    {
        const int PRODUCT_SEARCH = 20;

        OrderedBag<Item> bag = new OrderedBag<Item>();
        Random rand = new Random();

        for (int i = 0; i < 500000; i++)
        {
            bag.Add(new Item("ItemID: " + rand.Next(), rand.Next()));
        }

        var find = bag.Range(new Item("test", 0), true, new Item("test", 10000), true);

        int count = find.Count;
        if (count > PRODUCT_SEARCH)
        {
            count = PRODUCT_SEARCH;
        }

        for (int i = 0; i < count; i++)
        {
            Console.WriteLine("{0} ==== Price: {1}", find[i].Name, find[i].Price);
        }
    }
        public static void Main()
        {
            int    productsNumber = 500000;
            int    searchesNumber = 1000000;
            int    nameLenLow     = 3;
            int    nameLenUp      = 10;
            double priceLow       = 0.01;
            double priceUp        = 10000.00;
            int    takeCount      = 20;

            Stopwatch timer = new Stopwatch();

            timer.Start();
            OrderedBag <Product> productsBag = GenerateProducts(productsNumber,
                                                                nameLenLow, nameLenUp, priceLow, priceUp);

            timer.Stop();
            Console.WriteLine($"Time to fill SortedBag with {productsNumber} random products is {timer.Elapsed}");

            timer.Restart();
            for (int i = 0; i < searchesNumber; i++)
            {
                decimal lowerBoundary = RandomDecimal(priceLow, priceUp - 0.01);
                decimal upperBoundary = RandomDecimal((double)lowerBoundary + 0.01, priceUp);

                Product minProduct    = new Product("name", lowerBoundary);
                Product maxProduct    = new Product("name", upperBoundary);
                var     foundProducts = productsBag.Range(minProduct, true, maxProduct, false).Take(takeCount);
                //Console.WriteLine($"{i}.1: Range({lowerBoundary}-{upperBoundary}) - {foundProducts.First()}");
            }
            timer.Stop();
            Console.WriteLine($"Time to perform {searchesNumber} seaches by random price ranges is {timer.Elapsed}");
        }
Exemple #28
0
        static void Main(string[] args)
        {
            OrderedBag<Item> store = new OrderedBag<Item>();

            Random rnd = new Random();
            for (int i = 0; i < 500000; i++)
            {
                Item item = new Item("Product " + i, RandomPrice(rnd));
                store.Add(item);
            }

            var sw = new Stopwatch();
            sw.Start();

            IEnumerable<Item> searches = new List<Item>();
            for (int i = 0; i < 10000; i++)
            {
                double minPrice = RandomPrice(rnd);
                double maxPrice = RandomPrice(rnd);
                if (minPrice > maxPrice)
                {
                    double t = minPrice;
                    minPrice = maxPrice;
                    maxPrice = t;
                }

                searches = store.Range(new Item(minPrice), true, new Item(maxPrice), true).Take(20);
            }

            sw.Stop();

            Console.WriteLine("The time for 10 000 searches is:" + sw.Elapsed + "\nThe last result:\n" + string.Join("\n", searches));
        }
Exemple #29
0
        public static void Main()
        {
            OrderedBag <Product> products = new OrderedBag <Product>();

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

            decimal startOfInterval = 50M;
            decimal endOfInterval   = 500M;
            var     output          = new StringBuilder();

            for (int i = 0; i < 10000; i++)
            {
                var result = products.Range(
                    new Product {
                    Name = "", Price = startOfInterval
                }, true, new Product {
                    Name = "", Price = endOfInterval
                }, true)
                             .Take(20);

                output.AppendLine(string.Join(", ", result));

                startOfInterval += 10;
                endOfInterval   += 10;
            }

            Console.WriteLine(output.ToString());
        }
        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;
        }
Exemple #31
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 int RemoveAll(T element)
    {
        var node = new LinkedListNode <T>(element);

        var range = byOrder.Range(node, true, node, true);

        /*foreach (var item in range)
         * {
         *  byInsertion.Remove(item);
         * }*/

        int howMany = byInsertion.Count(x => x.Equals(element));

        while (howMany > 0)
        {
            byInsertion.Remove(node.Value);
            howMany--;
        }

        var count = byOrder.RemoveAllCopies(node);

        byOrderReversed.RemoveAllCopies(node);

        return(count);
    }
Exemple #33
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();
            }
        }
Exemple #34
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);
                }
            }
        }
Exemple #35
0
        public static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            OrderedBag <Product> catalog = new OrderedBag <Product>(new Comparison <Product>((x, y) => x.Price.CompareTo(y.Price)));

            for (int i = 0; i < TotalProducts; i++)
            {
                decimal productPrice   = randomGenerator.Next((int)MinProductPrice, (int)MaxProductPrice);
                string  productName    = "Product " + i;
                Product currentProduct = new Product(productPrice, productName);
                catalog.Add(currentProduct);
            }

            OrderedBag <Product> .View productsInRange = default(OrderedBag <Product> .View);

            for (int i = 0; i < SearchCount; i++)
            {
                productsInRange = catalog.Range(
                    new Product(MinProductRange + i * 0.001m, string.Empty), true,
                    new Product(MaxProductRange + i * 0.001m, string.Empty), true);
            }

            var firstNResults = productsInRange.Take(ResultCount);

            Console.WriteLine(string.Join(Environment.NewLine, firstNResults));

            sw.Stop();
            Console.WriteLine(sw.Elapsed);
        }
Exemple #36
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);
                //        }
                //    }
            }
        }
        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()
        {
            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);
        }
        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);
            }
        }
Exemple #40
0
        public static void Main(string[] args)
        {
            OrderedBag <Product> bag       = new OrderedBag <Product>();
            Stopwatch            stopwatch = new Stopwatch();

            Console.WriteLine("---Performance test (Adding)---");
            stopwatch.Start();
            int productsCount = 500000;

            for (int i = 0; i < productsCount; i++)
            {
                bag.Add(new Product("asd", i));
            }

            stopwatch.Stop();
            Console.WriteLine("{0} products added for {1}", productsCount, stopwatch.Elapsed);

            Console.WriteLine("Choose subrange of product's price:");
            Console.Write("From: ");
            double from = double.Parse(Console.ReadLine());

            Console.Write("To :");
            double to = double.Parse(Console.ReadLine());

            var subrangeProducts = bag.Range(
                new Product("asd", from), true,
                new Product("asd", to), true);

            if (subrangeProducts.Count >= 20)
            {
                Console.WriteLine("The first 20 products in this range are:");
                for (int i = 0; i < 20; i++)
                {
                    Console.WriteLine("Name: {0}, Price: {1}", subrangeProducts[i].Name, subrangeProducts[i].Price);
                }
            }
            else
            {
                Console.WriteLine("The products with price in this range are:");
                for (int i = 0; i < subrangeProducts.Count; i++)
                {
                    Console.WriteLine("Name: {0}, Price: {1}", subrangeProducts[i].Name, subrangeProducts[i].Price);
                }
            }

            Console.WriteLine("---Performance test (Searching)---");
            int     numberOfSearches = 10000;
            Product searchedProduct  = new Product("asd", 100);

            stopwatch.Reset();
            stopwatch.Start();
            for (int i = 0; i < numberOfSearches; i++)
            {
                bag.Contains(searchedProduct);
            }

            stopwatch.Stop();
            Console.WriteLine("{0} searches for {1}", numberOfSearches, stopwatch.Elapsed);
        }
Exemple #41
0
        private static List <Product> FindProductsByPrice(this OrderedBag <Product> bag, decimal minPrice, decimal maxPrice)
        {
            var foundProducts   = new List <Product>();
            var minPriceProduct = new Product("minPricedProduct", minPrice);
            var maxPriceProduct = new Product("maxPricedProduct", maxPrice);

            return(bag.Range(minPriceProduct, true, maxPriceProduct, true).Take(20).ToList());
        }
Exemple #42
0
 public static void PrintFirstTwentyProducts(OrderedBag<Product> products, int from, int to)
 {
     var firstTwentyProducts = products.Range(new Product("a", from), true, new Product("z", to), true).Take(20);
     foreach (var prod in firstTwentyProducts)
     {
         Console.WriteLine(prod.ToString());
     }
 }
Exemple #43
0
        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));
        }
Exemple #44
0
        // If uncomment the first result and input 200 for example, instead of "pricesearches", the program will hang out.
        private static List<Product> FindFirstTwentyProducts(OrderedBag<Product> products,double minRange,double maxRange)
        {
            //var result = products.Where(x => x.Price >= minRange && x.Price <= maxRange).OrderBy(x => x.Price).ToList();
            var result = products.Range(new Product("searchItem", maxRange), true,
                new Product("searchItem", minRange), true).ToList();

            return result;
        }
Exemple #45
0
        private static List <Product> SearchProductsByRange(OrderedBag <Product> products, decimal startPrice, decimal endPrice)
        {
            var startProduct = new Product("First Product", startPrice);
            var endProduct   = new Product("End Product", endPrice);
            var searchResult = products.Range(startProduct, true, endProduct, true);

            return(searchResult.Take(20).ToList());
        }
        public static IEnumerable<Product> GetProductsInRange(OrderedBag<Product> bag, int minPrice, int maxPrice, int count)
        {
            var result = bag
                         .Range(new Product("min", minPrice), true, new Product("max", maxPrice), true)
                         .Take(count);

            return result;
        }
Exemple #47
0
        private static void PrintTop20Results(int fromPrice, int toPrice, int searches)
        {
            var result = products.Range(new Product("start", fromPrice), true, new Product("end", toPrice), true).Take(searches);

            foreach (var product in result)
            {
                Console.WriteLine(product.Name + " " + product.Price);
            }
        }
Exemple #48
0
    private static Product[] FindFirst20ProductsInRange(OrderedBag <Product> productsInvetory, int startRange, int endRange)
    {
        Product startRangeProduct = new Product(string.Empty, startRange);
        Product endRangeProduct   = new Product(string.Empty, endRange);

        Product[] currentSearch = productsInvetory.Range(startRangeProduct, true, endRangeProduct, true).Take(20).ToArray();

        return(currentSearch);
    }
        private static List<Product> SearchProductsByRange(OrderedBag<Product> products, decimal startPrice,
            decimal endPrice)
        {
            var startProduct = new Product("First Product", startPrice);
            var endProduct = new Product("End Product", endPrice);
            var searchResult = products.Range(startProduct, true, endProduct, true);

            return searchResult.Take(20).ToList();
        }
        private static void PrintProductsInRange(int start, int end, OrderedBag<Product> products)
        {
            var result = products.Range(new Product("a", start), true, new Product("b", end), true).Take(20);

            foreach (var product in result)
            {
                Console.WriteLine(product);
            }
        }
        private static void PrintProductsInRange(int start, int end, OrderedBag <Product> products)
        {
            var result = products.Range(new Product("a", start), true, new Product("b", end), true).Take(20);

            foreach (var product in result)
            {
                Console.WriteLine(product);
            }
        }
        private ICollection <Product> FindTopProductsByPrice(OrderedBag <Product> productList, double startPrice, double endPrice)
        {
            var firstProductStartPrice    = productList.FirstOrDefault(x => x.Price >= startPrice);
            var lastProductEndPrice       = productList.LastOrDefault(x => x.Price <= endPrice);
            var productsInRange           = productList.Range(firstProductStartPrice, true, lastProductEndPrice, true);
            var firstgivenProductsInRange = productsInRange.Take(ProductsInRangeCount);

            return(firstgivenProductsInRange.ToList());
        }
        static IEnumerable<Product> GetProductsByPriceRange(OrderedBag<Product> products, decimal from, decimal to, int count)
        {
            var result = products.Range(
                    products.FirstOrDefault(x => x.Price >= from),
                    true,
                    products.LastOrDefault(x => x.Price <= to),
                    true).Take(count);

            return result;
        }
Exemple #54
0
 private static IEnumerable <Product> FindTop20MostExpensiveProducts(OrderedBag <Product> bag, decimal min, decimal max)
 {
     return(bag.Range(new Product {
         Name = "lowerRange", Price = min
     }, true, new Product {
         Name = "upperRange", Price = max
     }, true)
            .Take(22)
            .ToList());
 }
Exemple #55
0
        public static IEnumerable<Product> SearchRange(OrderedBag<Product> bag, int start, int end)
        {
            var collection = bag.Range(new Product("test", start), true, new Product("test", end), true);

            // For some (unknown) reason while debugging the "count" property of list will always be 0. However,
            // if you click on Results View in the debugger you will see that it contains the right number of elements.
            var list = collection.Take(20);

            return list;
        }
Exemple #56
0
        static void FilterBoth(double from, double to)
        {
            sb.Append("Ok: ");

            var testProduct1 = new Product("asd", "asd", from);
            var testProduct2 = new Product("asdd", "asdd", to);

            var products = byPrice.Range(testProduct1, true, testProduct2, true).Take(10);

            sb.AppendLine(string.Join(", ", products));
        }
        private static IEnumerable<Product> GetProductsInRange(OrderedBag<Product> products, int min, int max, int count)
        {
            var fromProduct = products.FirstOrDefault(p => p.Price >= min);
            var toProduct = products.FirstOrDefault(p => p.Price <= max);

            var filteredProducts = products
                .Range(fromProduct, true, toProduct, true)
                .Take(count);

            return filteredProducts;
        }
Exemple #58
0
        private static void PerformSerches(int count, OrderedBag <Product> collection)
        {
            for (int i = 0; i < count; i++)
            {
                var res = collection.Range(new Product("GenericProduct", rnd.Next(10)), true,
                                           new Product("GenericProduct", rnd.Next(5, 150)), true)
                          .Take(20);
//<-- Break point goes here :D
            }

            //Console.SpamTillUserRagequits
        }
Exemple #59
0
        private static void PerformSerches(int count, OrderedBag<Product> collection)
        {
            for (int i = 0; i < count; i++)
            {
                var res = collection.Range(new Product("GenericProduct", rnd.Next(10)), true,
                                           new Product("GenericProduct", rnd.Next(5,150)), true)
                                           .Take(20);
            //<-- Break point goes here :D
            }

            //Console.SpamTillUserRagequits
        }
        private static void MakeSearches(int count, int start, int end, OrderedBag<Product> products)
        {
            for (int i = 0; i < count; i++)
            {
                var result = products.Range(new Product("a", start), true, new Product("b", end), true).Take(20);

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