Exemplo n.º 1
0
        public SortedDictionary <string, long> UpdateDownloadTransfers(
            DownloadData downloads,
            SortedDictionary <string, long> downloadChanges,
            PopularityTransferData oldTransfers,
            PopularityTransferData newTransfers)
        {
            Guard.Assert(
                downloadChanges.Comparer == StringComparer.OrdinalIgnoreCase,
                $"Download changes should have comparer {nameof(StringComparer.OrdinalIgnoreCase)}");

            Guard.Assert(
                downloadChanges.All(x => downloads.GetDownloadCount(x.Key) == x.Value),
                "The download changes should match the latest downloads");

            // Downloads are transferred from a "from" package to one or more "to" packages.
            // The "oldTransfers" and "newTransfers" maps "from" packages to their corresponding "to" packages.
            // The "incomingTransfers" maps "to" packages to their corresponding "from" packages.
            var incomingTransfers = GetIncomingTransfers(newTransfers);

            _logger.LogInformation("Detecting changes in popularity transfers.");
            var transferChanges = _dataComparer.ComparePopularityTransfers(oldTransfers, newTransfers);

            _logger.LogInformation("{Count} popularity transfers have changed.", transferChanges.Count);

            // Get the transfer changes for packages affected by the download and transfer changes.
            var affectedPackages = GetPackagesAffectedByChanges(
                oldTransfers,
                newTransfers,
                incomingTransfers,
                transferChanges,
                downloadChanges);

            return(ApplyDownloadTransfers(
                       downloads,
                       newTransfers,
                       incomingTransfers,
                       affectedPackages));
        }
        private static IEnumerable <Question> GetTrailingCustomizations(int bookNum, SortedDictionary <QuestionKey, Customizations> customizations, Question lastQuestionInBook,
                                                                        Category category, int iQuestion)
        {
            if (customizations != null)
            {
                Debug.Assert(lastQuestionInBook != null && iQuestion > 0 && category != null,
                             $"Book {BCVRef.NumberToBookCode(bookNum)} has no built-in questions - cannot process customizations!");

                while (customizations.Any(c => c.Value.IsAdditionOrInsertion))
                {
                    var insertionForPreviousReference = customizations.FirstOrDefault(c => c.Value.IsAdditionOrInsertion && customizations.All(other => c.Value == other.Value || !other.Key.Matches(c.Key)));
                    var key = insertionForPreviousReference.Key;
                    if (key == null)
                    {
                        Debug.Assert(!customizations.Any(), $"Detected circular chain of customizations for book: {BCVRef.NumberToBookCode(bookNum)}. There were {customizations.Count} customizations that could not be processed!");
                        break;
                    }

                    var newQ = lastQuestionInBook.AddedQuestionAfter = insertionForPreviousReference.Value.PopQuestion(key);
                    if (!insertionForPreviousReference.Value.IsAdditionOrInsertion)
                    {
                        customizations.Remove(key);
                    }
                    category.Questions.Add(newQ);
                    foreach (Question question in GetCustomizations(newQ, category, iQuestion, customizations))
                    {
                        lastQuestionInBook = question;
                        yield return(question);

                        iQuestion++;
                    }
                }
            }
        }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Gets (possibly modified form of) the given phrase along with any inserted (before)
        /// or added (after) phrases. Also note any "Deletions" (i.e., exclusions).
        /// </summary>
        /// ------------------------------------------------------------------------------------
        private static IEnumerable <Question> GetCustomizations(Question q, Category category, int index,
                                                                SortedDictionary <QuestionKey, Customizations> customizations, bool processAllAdditionsForRef = false)
        {
            Customizations customizationsForQuestion;

            if (customizations.TryGetValue(q, out customizationsForQuestion))
            {
                customizations.Remove(q);
                customizationsForQuestion.ApplyToQuestion(q);
                if (q.InsertedQuestionBefore != null)
                {
                    category.Questions.Insert(index, q.InsertedQuestionBefore);
                    foreach (Question customQuestion in GetCustomizations(q.InsertedQuestionBefore, category, index, customizations))
                    {
                        yield return(customQuestion);

                        index++;
                    }
                }
            }
            if (q.InsertedQuestionBefore == null)
            {
                var insertionForPreviousReference = customizations.LastOrDefault(c => c.Value.IsInsertionAtOrBeforeReference(q, category.Questions, processAllAdditionsForRef) &&
                                                                                 customizations.All(other => other.Value == c.Value || !other.Key.Matches(c.Key)));
                var key = insertionForPreviousReference.Key;
                if (key == null)
                {
                    Debug.Assert(!customizations.Any(c => c.Value.IsInsertionAtOrBeforeReference(q, category.Questions, processAllAdditionsForRef)));
                    // Clean up any preceding deletions/modifications that didn't match anything
                    customizations.RemoveAll(c => c.Key.IsAtOrBeforeReference(q, processAllAdditionsForRef));
                }
                else
                {
                    var newQ = q.InsertedQuestionBefore = insertionForPreviousReference.Value.PopQuestion(key);
                    category.Questions.Insert(index, newQ);
                    // We now want to remove this, but only if it doesn't have additional pending insertions or deletions hanging off it.
                    if (!insertionForPreviousReference.Value.IsAdditionOrInsertion)
                    {
                        customizations.Remove(key);
                    }
                    foreach (Question customQuestion in GetCustomizations(newQ, category, index, customizations, true))
                    {
                        yield return(customQuestion);

                        index++;
                    }
                }
            }

            yield return(q);

            if (q.AddedQuestionAfter != null)
            {
                category.Questions.Insert(index + 1, q.AddedQuestionAfter);
                foreach (Question tpAdded in GetCustomizations(q.AddedQuestionAfter, category, index + 1, customizations))
                {
                    yield return(tpAdded);

                    index++;
                }
            }
        }
Exemplo n.º 4
0
 public bool IsAdded()
 {
     return(Cells.All(c => c.Value.Status == ExcelCellStatus.Added));
 }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            Dictionary <string, int> cocktailsAndPoints = new Dictionary <string, int>();

            cocktailsAndPoints.Add("Mimosa", 150);
            cocktailsAndPoints.Add("Daiquiri", 250);
            cocktailsAndPoints.Add("Sunshine", 300);
            cocktailsAndPoints.Add("Mojito", 400);

            SortedDictionary <string, int> cocktailsAndCounts = new SortedDictionary <string, int>();

            cocktailsAndCounts.Add("Mimosa", 0);
            cocktailsAndCounts.Add("Daiquiri", 0);
            cocktailsAndCounts.Add("Sunshine", 0);
            cocktailsAndCounts.Add("Mojito", 0);

            Queue <int> ingredients = new Queue <int>(Console.ReadLine()
                                                      .Split(" ", StringSplitOptions.RemoveEmptyEntries)
                                                      .Select(int.Parse));

            Stack <int> freshness = new Stack <int>(Console.ReadLine()
                                                    .Split(" ", StringSplitOptions.RemoveEmptyEntries)
                                                    .Select(int.Parse));

            while (ingredients.Any() && freshness.Any())
            {
                int currentIngredient = ingredients.Dequeue();

                if (currentIngredient == 0)
                {
                    continue;
                }

                int currentFreshness = freshness.Pop();

                int product = currentIngredient * currentFreshness;

                bool isMade = cocktailsAndPoints.Any(x => x.Value == product);
                if (isMade)
                {
                    string currentCocktail = cocktailsAndPoints
                                             .Where(x => x.Value == product)
                                             .FirstOrDefault()
                                             .Key;

                    cocktailsAndCounts[currentCocktail]++;
                }
                else
                {
                    currentIngredient += 5;
                    ingredients.Enqueue(currentIngredient);
                }
            }

            bool isSuccess = cocktailsAndCounts.All(x => x.Value > 0);

            if (isSuccess)
            {
                Console.WriteLine("It's party time! The cocktails are ready!");
            }
            else
            {
                Console.WriteLine("What a pity! You didn't manage to prepare all cocktails.");
            }

            bool areIngredients = ingredients.Any();

            if (areIngredients)
            {
                Console.WriteLine($"Ingredients left: {ingredients.Sum()}");
            }

            foreach (var kvp in cocktailsAndCounts)
            {
                string currentCocktail = kvp.Key;
                int    count           = kvp.Value;

                bool hasToPrint = count > 0;
                if (hasToPrint)
                {
                    Console.WriteLine($" # {currentCocktail} --> {count}");
                }
            }
        }
        static void Main(string[] args)
        {
            Dictionary <string, int> materialsAndPoints = new Dictionary <string, int>();

            materialsAndPoints.Add("Glass", 25);
            materialsAndPoints.Add("Aluminium", 50);
            materialsAndPoints.Add("Lithium", 75);
            materialsAndPoints.Add("Carbon fiber", 100);

            SortedDictionary <string, int> materialsAndCounts = new SortedDictionary <string, int>();

            materialsAndCounts.Add("Glass", 0);
            materialsAndCounts.Add("Aluminium", 0);
            materialsAndCounts.Add("Lithium", 0);
            materialsAndCounts.Add("Carbon fiber", 0);

            Queue <int> liquids = new Queue <int>(Console.ReadLine()
                                                  .Split(" ", StringSplitOptions.RemoveEmptyEntries)
                                                  .Select(int.Parse));

            Stack <int> items = new Stack <int>(Console.ReadLine()
                                                .Split(" ", StringSplitOptions.RemoveEmptyEntries)
                                                .Select(int.Parse));

            while (liquids.Any() && items.Any())
            {
                int currentLiquid = liquids.Dequeue();
                int currentItem   = items.Pop();

                int sum = currentLiquid + currentItem;

                bool isMade = materialsAndPoints.Any(x => x.Value == sum);
                if (isMade)
                {
                    string currentMaterial = materialsAndPoints
                                             .Where(x => x.Value == sum)
                                             .FirstOrDefault()
                                             .Key;

                    materialsAndCounts[currentMaterial]++;
                }
                else
                {
                    currentItem += 3;
                    items.Push(currentItem);
                }
            }

            bool isSuccess = materialsAndCounts.All(x => x.Value > 0);

            if (isSuccess)
            {
                Console.WriteLine("Wohoo! You succeeded in building the spaceship!");
            }
            else
            {
                Console.WriteLine("Ugh, what a pity! You didn't have enough materials to build the spaceship.");
            }

            bool areLiquids = liquids.Any();

            if (areLiquids)
            {
                Console.WriteLine($"Liquids left: {string.Join(", ", liquids)}");
            }
            else
            {
                Console.WriteLine("Liquids left: none");
            }

            bool areItems = items.Any();

            if (areItems)
            {
                Console.WriteLine($"Physical items left: {string.Join(", ", items)}");
            }
            else
            {
                Console.WriteLine("Physical items left: none");
            }

            Console.WriteLine(string.Join(Environment.NewLine, materialsAndCounts
                                          .Select(x => $"{x.Key}: {x.Value}")));
        }
Exemplo n.º 7
0
        IReadOnlyDictionary <float, T> IConvertibleCurve <T> .ToLinearCurve()
        {
            if (_Keys.Count == 0)
            {
                return(new Dictionary <float, T>());
            }

            if (_Keys.All(item => item.Value.Degree == 1))
            {
                return(_Keys.ToDictionary(item => item.Key, item => CloneValue(item.Value.Point)));
            }

            var d = new Dictionary <float, T>();

            if (_Keys.Count == 0)
            {
                return(d);
            }

            if (Keys.Count == 1)
            {
                var k = _Keys.First();
                d[k.Key] = k.Value.Point;
                return(d);
            }

            var orderedKeys = _Keys.Keys.ToList();

            for (int i = 0; i < orderedKeys.Count - 1; ++i)
            {
                var a = orderedKeys[i + 0];
                var b = orderedKeys[i + 1];

                var sa = _Keys[a];
                var sb = _Keys[b];

                switch (sa.Degree)
                {
                case 0:     // simulate a step with an extra key
                    d[a] = sa.Point;
                    d[b - float.Epsilon] = sa.Point;
                    d[b] = sb.Point;
                    break;

                case 1:
                    d[a] = sa.Point;
                    d[b] = sb.Point;
                    break;

                case 3:
                    var t = a;
                    while (t < b)
                    {
                        d[t] = this.GetPoint(t);
                        t   += 1.0f / 30.0f;
                    }

                    break;

                default: throw new NotImplementedException();
                }
            }

            return(d);
        }
Exemplo n.º 8
0
 /// <summary>
 /// An overload of the main method providing support for sorted dictionaries
 /// </summary>
 /// <param name="prms"></param>
 /// <returns></returns>
 public bool HasAllPermissions(SortedDictionary<string, Permission> prms)
 {
     return prms.All(perm => HasPermission(perm.Key));
 }
        public void TestManyOperations()
        {
            // Create some random, but unique items
            // Use a fixed seed for consistency in results
            Random        random       = new Random(1);
            HashSet <int> baseItemsSet = new HashSet <int>();

            while (baseItemsSet.Count < 1_100_000)
            {
                baseItemsSet.Add(random.Next());
            }

            // Create 2 collections, 1 to test, and 1 to compare against
            var testCollection   = new ConcurrentObservableSortedDictionary <string, string>();
            var sortedDictionary = new SortedDictionary <string, string>();

            // Create 1,000,000 items to add and insert
            var itemsToAdd =
                baseItemsSet
                .Take(1_000_000)
                .Select(x => Swordfish.NET.Collections.KeyValuePair.Create($"Key {x}", $"Value {x}"))
                .ToList();

            // Create 100,000 items to insert
            var itemsToInsert =
                baseItemsSet
                .Skip(1_000_000)
                .Take(100_000)
                .Select(x => Swordfish.NET.Collections.KeyValuePair.Create($"Insert Key {x}", $"Insert Value {x}"))
                .ToList();

            // Create items to remove
            var itemsToRemove =
                itemsToInsert
                .Take(1000)
                .ToList();

            foreach (var item in itemsToAdd)
            {
                sortedDictionary.Add(item.Key, item.Value);
                testCollection.Add(item.Key, item.Value);
            }

            // Check items are equal count
            Assert.IsTrue(sortedDictionary.Count == testCollection.Count, "Added Items correct count");

            // Check items are equal order
            var allEqualAfterAdd =
                sortedDictionary
                .Zip(testCollection, (a, b) => (a.Key == b.Key) && (a.Value == b.Value))
                .All(a => a);

            Assert.IsTrue(allEqualAfterAdd, "Added items correct order");


            // Test inserting items

            int insertIndex = itemsToInsert.Count + 100;

            foreach (var item in itemsToInsert)
            {
                // Naturally sorted dictionary doesn't support insert at
                sortedDictionary.Add(item.Key, item.Value);
                // We have the function but it's there for other reasons
                testCollection.Insert(insertIndex, item);

                insertIndex--;
            }

            // Check items are equal count
            Assert.IsTrue(sortedDictionary.Count == testCollection.Count, "Items correct count after inserting");

            // Check items are equal order
            var allEqualAfterInsert =
                sortedDictionary
                .Zip(testCollection, (a, b) => (a.Key == b.Key) && (a.Value == b.Value))
                .All(a => a);

            Assert.IsTrue(allEqualAfterAdd, "Items correct order after insert");

            // Test removing items

            foreach (var item in itemsToRemove)
            {
                sortedDictionary.Remove(item.Key);
                testCollection.Remove(item.Key);
            }

            // Check items are equal count
            Assert.IsTrue(sortedDictionary.Count == testCollection.Count, "Items correct count after removing");

            // Check items are equal order
            var allEqualAfterRemove =
                sortedDictionary
                .Zip(testCollection, (a, b) => (a.Key == b.Key) && (a.Value == b.Value))
                .All(a => a);

            Assert.IsTrue(allEqualAfterRemove, "Items correct order after removing");

            // Test contains

            var containsAll = sortedDictionary
                              .All(kv => testCollection.Contains(kv));

            Assert.IsTrue(containsAll, "Contains all the items is true");

            var containsNone = itemsToRemove
                               .Any(kv => testCollection.ContainsKey(kv.Key));

            Assert.IsFalse(containsNone, "Contains any of the removed items is false");


            // Test removing at

            var sortedList = new SortedList <string, string>(sortedDictionary);

            int removeAtIndex = sortedDictionary.Count - 30;

            while (removeAtIndex >= 0 && sortedDictionary.Count > 0)
            {
                sortedList.RemoveAt(removeAtIndex);
                testCollection.RemoveAt(removeAtIndex);
                removeAtIndex -= 30;
            }

            // Check items are equal count
            Assert.IsTrue(sortedList.Count == testCollection.Count, "Items correct count after removing at index");

            // Check items are equal order
            var allEqualAfterRemoveAt =
                sortedList
                .Zip(testCollection, (a, b) => (a.Key == b.Key) && (a.Value == b.Value))
                .All(a => a);

            Assert.IsTrue(allEqualAfterRemoveAt, "Items correct order after removing at index");

            var list =
                sortedList
                .Select(x => x.Key)
                .ToList();

            bool getItemCorrect = true;

            for (int i = 0; i < list.Count; ++i)
            {
                getItemCorrect &= testCollection.GetItem(i).Key == list[i];
            }

            Assert.IsTrue(getItemCorrect, "Get item by index correct");

            /*
             *
             * [TestMethod]
             * public void AddRangeTest()
             * {
             * Assert.Fail();
             * }
             *
             * [TestMethod]
             * public void RemoveTest()
             * {
             * Assert.Fail();
             * }
             *
             * [TestMethod]
             * public void RemoveRangeTest()
             * {
             * Assert.Fail();
             * }
             *
             * [TestMethod]
             * public void ToStringTest()
             * {
             * Assert.Fail();
             * }
             *
             * [TestMethod]
             * public void GetEnumeratorTest()
             * {
             * Assert.Fail();
             * }
             *
             * [TestMethod]
             * public void ClearTest()
             * {
             * Assert.Fail();
             * }
             *
             * [TestMethod]
             * public void ContainsTest()
             * {
             * Assert.Fail();
             * }
             *
             * [TestMethod]
             * public void CopyToTest()
             * {
             * Assert.Fail();
             * }
             */
        }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            SortedDictionary <string, int> bombCount = new SortedDictionary <string, int>();

            bombCount["Cherry Bombs"]      = 0;
            bombCount["Datura Bombs"]      = 0;
            bombCount["Smoke Decoy Bombs"] = 0;

            Dictionary <int, string> bombData = new Dictionary <int, string>();

            bombData[40]  = "Datura Bombs";
            bombData[60]  = "Cherry Bombs";
            bombData[120] = "Smoke Decoy Bombs";

            int[] bombEfects = Console.ReadLine().Split(", ", StringSplitOptions.RemoveEmptyEntries)
                               .Select(int.Parse).ToArray();
            int[] bombCasing = Console.ReadLine().Split(", ", StringSplitOptions.RemoveEmptyEntries)
                               .Select(int.Parse).ToArray();

            Queue <int> effectsQueue = new Queue <int>(bombEfects);
            Stack <int> casingStack  = new Stack <int>(bombCasing);

            bool filledPouch = false;

            while (effectsQueue.Count > 0 && casingStack.Count > 0)
            {
                int sumEffectCasing = effectsQueue.Peek() + casingStack.Peek();
                if (bombData.ContainsKey(sumEffectCasing))
                {
                    bombCount[bombData[sumEffectCasing]]++;
                    effectsQueue.Dequeue();
                    casingStack.Pop();
                }
                else
                {
                    casingStack.Push(casingStack.Pop() - 5);
                }
                if (bombCount.All(x => x.Value >= 3))
                {
                    filledPouch = true;
                    break;
                }
            }
            if (filledPouch)
            {
                Console.WriteLine("Bene! You have successfully filled the bomb pouch!");
            }
            else
            {
                Console.WriteLine("You don't have enough materials to fill the bomb pouch.");
            }

            if (effectsQueue.Count > 0)
            {
                int[] effectsRemain = effectsQueue.ToArray();
                Console.WriteLine("Bomb Effects: " + string.Join(", ", effectsRemain));
            }
            else
            {
                Console.WriteLine("Bomb Effects: empty");
            }

            if (casingStack.Count > 0)
            {
                int[] casingsRemain = casingStack.ToArray();
                Console.WriteLine("Bomb Casings: " + string.Join(", ", casingsRemain));
            }
            else
            {
                Console.WriteLine("Bomb Casings: empty");
            }
            foreach (var item in bombCount)
            {
                Console.WriteLine($"{item.Key}: {item.Value}");
            }
        }