HarryPotter.ShoppingCartCalculator.Calculate C# (CSharp) Method

Calculate() public method

public Calculate ( List shoppingCart ) : decimal
shoppingCart List
return decimal
        public decimal Calculate(List<Book> shoppingCart)
        {
            // Generate list of all sets of unique books in cart
            var setsOfUniqueBooks = new List<List<Book>>();

            while (shoppingCart.Count > 0)
            {
                var uniqueSet = new List<Book>();
                for (int i = 1; i <= 5; i++)
                {
                    var book = shoppingCart.FirstOrDefault(s => s.id == i);
                    if (book != null)
                    {
                        uniqueSet.Add(book);
                        shoppingCart.Remove(book);
                    }
                }
                setsOfUniqueBooks.Add(uniqueSet);
            }

            // If there is a set of 5 unique books and a set of 3 unique books, replace them with 2 sets of 4 unique books
            while (setsOfUniqueBooks.Any(set => set.Count == 3) && setsOfUniqueBooks.Any(set => set.Count == 5))
            {
                var setOfFive = setsOfUniqueBooks.FirstOrDefault(set => set.Count == 5);
                var setOfThree = setsOfUniqueBooks.FirstOrDefault(set => set.Count == 3);

                if (setOfThree != null & setOfFive != null)
                {
                    var bookNotInSetOfThree = (from books in setOfThree
                        from books2 in setOfFive
                        where books.id != books2.id
                        select books2).First();

                    setOfFive.Remove(bookNotInSetOfThree);
                    setOfThree.Add(bookNotInSetOfThree);
                }
            }
            return setsOfUniqueBooks.Sum(set => CalculateDiscount(set));
        }

Usage Example

Ejemplo n.º 1
0
        public void BuyTwoSetsOfFiveAndTwoSetsOfThree()
        {
            var shoppingCart = new List <Book>();
            var calculator   = new ShoppingCartCalculator();

            for (int i = 0; i < 4; i++)
            {
                shoppingCart.Add(new Book(1));
            }

            for (int i = 0; i < 4; i++)
            {
                shoppingCart.Add(new Book(2));
            }
            for (int i = 0; i < 4; i++)
            {
                shoppingCart.Add(new Book(3));
            }
            for (int i = 0; i < 2; i++)
            {
                shoppingCart.Add(new Book(4));
            }
            for (int i = 0; i < 2; i++)
            {
                shoppingCart.Add(new Book(5));
            }

            var actual = calculator.Calculate(shoppingCart);

            Assert.AreEqual(102.4M, actual);
        }
All Usage Examples Of HarryPotter.ShoppingCartCalculator::Calculate
ShoppingCartCalculator