Ejemplo n.º 1
0
        /// <summary>
        ///     Returns the number of unique paths along the lattice lines of a 2d grid,
        ///     being able to only move down or to the right at each point.
        /// </summary>
        /// <param name="width">Width of the 2d grid.</param>
        /// <param name="height">Height of the 2d grid.</param>
        /// <returns>The number of paths through the lattice points of the grid.</returns>
        public static long NumLatticePaths2DDownAndRight(int width, int height)
        {
            var toCheck = new Dictionary<Grid2D, long>();
            toCheck.Add(new Grid2D {Width = width, Height = height}, 1);

            var pathLength = 0L;
            while (toCheck.Count != 0)
            {
                var gridInfo = toCheck.First();
                var grid = gridInfo.Key;
                var count = gridInfo.Value;

                toCheck.Remove(grid);

                if (grid.Width == 1)
                {
                    pathLength += count * (grid.Height + 1);
                }
                else if (grid.Height == 1)
                {
                    pathLength += count * (grid.Width + 1);
                }
                else
                {
                    var subGrid1 = new Grid2D {Width = grid.Width, Height = grid.Height - 1};
                    var subGrid2 = new Grid2D {Width = grid.Width - 1, Height = grid.Height};

                    toCheck.AddOrIncrement(subGrid1, count, count);
                    toCheck.AddOrIncrement(subGrid2, count, count);
                }
            }

            return pathLength;
        }
        public void DictionaryExt_Test003_AddTwoDuplicate()
        {
            Dictionary<string, int> dictionary = new Dictionary<string, int>();

            dictionary.AddOrIncrement(__keyYellow);
            dictionary.AddOrIncrement(__keyYellow);

            Assert.AreEqual<int>(2, dictionary[__keyYellow]);
        }
Ejemplo n.º 3
0
    /// <summary>
    /// Expands the polymer template as specified by the instructions.
    /// </summary>
    /// <param name="instructions">The instructions to expand a polymer from.</param>
    /// <param name="steps">The number of steps to expand the polymer by.</param>
    /// <returns>
    /// The polymer's score after expansion.
    /// </returns>
    public static long Expand(IList <string> instructions, int steps)
    {
        string template = instructions[0];

        var insertions = new Dictionary <string, char>(instructions.Count - 2);

        foreach (string instruction in instructions.Skip(2))
        {
            string[] split   = instruction.Split(" -> ");
            string   pair    = split[0];
            char     element = split[1][0];

            insertions[pair] = element;
        }

        var pairCounts = new Dictionary <string, long>();

        for (int i = 0; i < template.Length - 1; i++)
        {
            char first  = template[i];
            char second = template[i + 1];

            string pair = first + string.Empty + second;

            pairCounts.AddOrIncrement(pair, 1);
        }

        for (int i = 1; i <= steps; i++)
        {
            foreach ((string pair, long count) in pairCounts.ToArray())
            {
                if (count > 0 && insertions.TryGetValue(pair, out char element))
                {
                    pairCounts[pair] -= count;

                    string pair1 = pair[0] + string.Empty + element;
                    string pair2 = element + string.Empty + pair[1];

                    pairCounts.AddOrIncrement(pair1, count, count);
                    pairCounts.AddOrIncrement(pair2, count, count);
                }
            }
        }

        var frequencies = new Dictionary <char, long>();

        foreach ((string pair, long count) in pairCounts)
        {
            frequencies.AddOrIncrement(pair[0], count, count);
            frequencies.AddOrIncrement(pair[1], count, count);
        }

        long max = frequencies.Values.Max();
        long min = frequencies.Values.Min();

        return((max - min + 1) / 2);
    }
        public void DictionaryExt_Test005_AddTwoDuplicateDifferenctCase_CaseInsensitiveDictionary()
        {
            Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);

            dictionary.AddOrIncrement(__keyYellow);
            dictionary.AddOrIncrement(__keyYellow.ToLower());

            Assert.AreEqual<int>(2, dictionary[__keyYellow]);
        }
        public void DictionaryExt_Test004_AddTwoDuplicateDifferenctCase()
        {
            Dictionary<string, int> dictionary = new Dictionary<string, int>();

            dictionary.AddOrIncrement(__keyYellow);
            dictionary.AddOrIncrement(__keyYellow.ToLower());

            Assert.AreEqual<int>(1, dictionary[__keyYellow]);
            Assert.AreEqual<int>(1, dictionary[__keyYellow.ToLower()]);
        }
        public void DictionaryExt_Test002_AddTwoUnique()
        {
            Dictionary<string, int> dictionary = new Dictionary<string, int>();

            dictionary.AddOrIncrement(__keyYellow);
            dictionary.AddOrIncrement(__keyGreen);

            Assert.AreEqual<int>(1, dictionary[__keyYellow]);
            Assert.AreEqual<int>(1, dictionary[__keyGreen]);
        }
Ejemplo n.º 7
0
        internal static long GetVarValueMap(LinearExpr e, long initial_coeff, Dictionary <IntVar, long> dict,
                                            Queue <Term> terms)
        {
            long       constant    = 0;
            long       coefficient = initial_coeff;
            LinearExpr expr        = e;

            terms.Clear();

            do
            {
                switch (expr)
                {
                case LinearExprBuilder builder:
                    constant += coefficient * builder.Offset;
                    if (coefficient == 1)
                    {
                        foreach (Term sub in builder.Terms)
                        {
                            terms.Enqueue(sub);
                        }
                    }
                    else
                    {
                        foreach (Term sub in builder.Terms)
                        {
                            terms.Enqueue(new Term(sub.expr, sub.coefficient * coefficient));
                        }
                    }
                    break;

                case IntVar intVar:
                    dict.AddOrIncrement(intVar, coefficient);
                    break;

                case NotBoolVar notBoolVar:
                    dict.AddOrIncrement((IntVar)notBoolVar.Not(), -coefficient);
                    constant += coefficient;
                    break;

                default:
                    throw new ArgumentException("Cannot evaluate '" + expr + "' in an integer expression");
                }

                if (!terms.TryDequeue(out var term))
                {
                    break;
                }
                expr        = term.expr;
                coefficient = term.coefficient;
            } while (true);

            return(constant);
        }
Ejemplo n.º 8
0
        private void Advance(string source, Dictionary <char, int> targetCountMap,
                             Dictionary <char, int> currentCountMap, int searchLength,
                             ref int numberOfChars, ref int currentIndex, ref int leftBoundry)
        {
            // Shortcut: if we find a char in source string that is not in search string,
            // reset the current count map and leftBoundry
            while (currentIndex < source.Length &&
                   !targetCountMap.ContainsKey(source[currentIndex]))
            {
                currentIndex++;
                numberOfChars = 0;
                currentCountMap.Clear();
                leftBoundry = currentIndex;
            }

            if (currentIndex < source.Length)
            {
                currentCountMap.AddOrIncrement(source[currentIndex]);
                numberOfChars++;
            }

            if (currentIndex - searchLength >= leftBoundry)
            {
                currentCountMap.RemoveOrDecrement(source[currentIndex - searchLength]);
                numberOfChars--;
            }

            currentIndex++;
        }
Ejemplo n.º 9
0
        public void AddOrIncrement_AddingNewKeyWithValue_ReturnNewlyAddedElementWithValue()
        {
            const string key        = "New";
            var          dictionary = new Dictionary <string, int>();

            dictionary.AddOrIncrement(key, 1);

            dictionary.Should().Contain(key, 1);
        }
Ejemplo n.º 10
0
            private void AddValue(int value, int count = 1)
            {
                if (value == targetSum)
                {
                    TotalCount += count;
                }

                possibleSums.AddOrIncrement(value, count);
            }
Ejemplo n.º 11
0
        internal void ProcessingData()
        {
            try
            {
                if (_lock)
                {
                    return;
                }

                _lock = true;

                var method = UtilHelper.GetMethodName(MethodBase.GetCurrentMethod());
                _logger?.Info($"{method} => start");
                var watch = System.Diagnostics.Stopwatch.StartNew();

                var data = DataReaderHelper.GetData(
                    _dataReaders, _filtersValidator, _filtersValidatorRepository, _aggregatorsValidator, _aggregatorsValidatorRepository);
                if (!data.Any())
                {
                    _logger?.Debug("No data found...");
                    return;
                }

                var sendedMessages = new Dictionary <SendedMessages, int>();
                foreach (var message in data)
                {
                    if (!_clientsManager.Send(message))
                    {
                        _logger?.Debug("No clients defined to send...");
                        return;
                    }
                    var sendedMessage = new SendedMessages {
                        Name = message.LogicalStorage, Id = message.ReaderId
                    };
                    sendedMessages.AddOrIncrement(sendedMessage, 1);
                }

                foreach (var message in sendedMessages)
                {
                    _logger?.Debug($"Sended: {message.Value} messages from {message.Key}");
                }

                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                _logger?.Info($"{method} => end, Time taken: {elapsedMs}ms");
            }
            catch (Exception ex)
            {
                _logger?.Error(ex.Message);
            }
            finally
            {
                _lock = false;
            }
        }
Ejemplo n.º 12
0
        public static Dictionary <char, int> GetCountMap(string input)
        {
            Dictionary <char, int> countMap = new Dictionary <char, int>();

            for (int i = 0; i < input.Length; i++)
            {
                countMap.AddOrIncrement(input[i]);
            }

            return(countMap);
        }
Ejemplo n.º 13
0
        public void AddOrIncrement_IncrementingValueForExistKeyWithGivenValue_ReturnIncrementedValueForKeyWithoutGivenValue()
        {
            const string key        = "New";
            var          dictionary = new Dictionary <string, int>()
            {
                { key, 2 }
            };

            dictionary.AddOrIncrement(key, 50);

            dictionary.Should().Contain(key, 3);
        }
Ejemplo n.º 14
0
        public void ProcessText()
        {
            Dictionary<string, int> sorted = new Dictionary<string, int>();

            string[] words = this.TextToSplit.RemovePunctuation().Split(new char[] { ' ' });

            foreach (var word in words)
                if (word.Trim() != string.Empty)
                    sorted.AddOrIncrement(word.Trim());

            this.Breakdown = sorted;

        }
Ejemplo n.º 15
0
        public static void Test_WordCount(string[] args)
        {
            Console.WriteLine("Please enter data to split:\n");

            var data = Console.ReadLine();

            Dictionary<string, int> sorted = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);

            string[] words = data.RemovePunctuation().Split(new char[] { ' ' });

            foreach (var word in words)
                if (word.Trim() != string.Empty)
                    sorted.AddOrIncrement(word.Trim());

            foreach (var entry in sorted)
                Console.WriteLine("{0} - {1}", entry.Key, entry.Value);

        }
        private static void ShowAssetSelectionStatistics()
        {
            Dictionary <Type, int> types       = new Dictionary <Type, int>();
            List <string>          objectNames = new List <string>();
            int   objectCounter  = 0;
            float memoryFileSize = 0f;
            var   objects        = Selection.objects;

            if (objects == null)
            {
                return;
            }

            foreach (var current in objects)
            {
                objectCounter++;
                if (EditorUtility.DisplayCancelableProgressBar("Analyzing game objects",
                                                               "Analyzing object " + objectCounter + " of " + objects.Length,
                                                               (float)objectCounter / (float)objects.Length))
                {
                    Debug.Log("Process canceled");
                    break;
                }

                // TODO navigate through folders if it is one
                objectNames.Add(current.name);
                memoryFileSize += UnityEngine.Profiling.Profiler.GetRuntimeMemorySizeLong(current);
                types.AddOrIncrement(current.GetType());
            }

            EditorUtility.ClearProgressBar();
            Debug.Log(objectNames.ToFormattedString("", ",\n", ""));
            EditorUtility.DisplayDialog("Selection statistics",
                                        string.Format("--------------------------\n" +
                                                      "Selected objects: {0} \n" +
                                                      "Memory usage: {1} \n" +
                                                      "---------------------------\n" +
                                                      "{2} \n" +
                                                      "--------------------------\n",
                                                      string.Format("{0:n0}", objectCounter),
                                                      GetFileSize(memoryFileSize),
                                                      types.ToFormattedString("Types: \n - ", ", \n - ", ": ", "")),
                                        "OK");
        }
Ejemplo n.º 17
0
        private void Close()
        {
            var method = UtilHelper.GetMethodName(MethodBase.GetCurrentMethod());

            _logger?.Info($"{method} => start");
            var watch = System.Diagnostics.Stopwatch.StartNew();

            if (!CheckTimeForCloseApp(_lifetime))
            {
                _logger?.Debug("Not time to die..."); return;
            }

            try
            {
                var data = _dataReader.GetData();

                var sendedMessages = new Dictionary <string, int>();
                foreach (var message in data)
                {
                    _clientsManager.Send(message);
                    sendedMessages.AddOrIncrement(message.LogicalStorage, 1);
                }

                foreach (var message in sendedMessages)
                {
                    _logger?.Debug($"Sended: {message.Value} messages about application exit from {message.Key}");
                }

                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                _logger?.Info($"{method} => end, Time taken: {elapsedMs}ms");
            }
            catch (Exception ex)
            {
                _logger?.Error(ex.Message);
            }
            finally
            {
                _timer.Stop();
                Environment.Exit(0);
            }
        }
Ejemplo n.º 18
0
    /// <summary>
    /// Calculates the product of the guard who slept the most and the minute they were asleep the most from the specified log.
    /// </summary>
    /// <param name="log">The log of guard activity.</param>
    /// <returns>
    /// The product of the guard who slept the most and the minute they were asleep the most as specified by <paramref name="log"/>
    /// and the product of the minute a guard was most asleep and the guard's Id.
    /// </returns>
    public static (int GuardMinute, int MinuteGuard) GetSleepiestGuardsMinutes(IEnumerable <string> log)
    {
        var parsedAndSortedLog = log
                                 .Select((p) => LogEntry.Parse(p))
                                 .OrderBy((p) => p.Timestamp)
                                 .ToList();

        var groupedLog = parsedAndSortedLog.GroupBy((p) => p.Timestamp.Date);

        var guardsAsleepByMinute = groupedLog
                                   .Select((p) => p.Key)
                                   .Distinct()
                                   .ToDictionary((k) => k, (v) => new int[60]);

        var  first         = parsedAndSortedLog[0];
        int  lastGuard     = first.Id !.Value;
        var  lastTimestamp = first.Timestamp;
        bool isAwake       = true;

        var midnight  = TimeSpan.Zero;
        var oneAM     = TimeSpan.FromHours(1);
        var oneMinute = TimeSpan.FromMinutes(1);

        foreach (var day in groupedLog)
        {
            foreach (var entry in day)
            {
                if (!isAwake &&
                    lastTimestamp.TimeOfDay >= midnight &&
                    lastTimestamp.TimeOfDay < oneAM)
                {
                    var   time         = lastTimestamp;
                    int[] midnightHour = guardsAsleepByMinute[day.Key];

                    while (time.TimeOfDay < oneAM && time < entry.Timestamp)
                    {
                        midnightHour[time.TimeOfDay.Minutes] = lastGuard;
                        time = time.Add(oneMinute);
                    }
                }

                if (entry.Wakefulness.HasValue)
                {
                    isAwake = entry.Wakefulness.Value;
                }
                else if (entry.Id.HasValue)
                {
                    lastGuard = entry.Id.Value;
                }

                lastTimestamp = entry.Timestamp;
            }
        }

        var sleepinessPerGuard = parsedAndSortedLog
                                 .Where((p) => p.Id.HasValue)
                                 .Select((p) => p.Id.GetValueOrDefault())
                                 .Distinct()
                                 .ToDictionary((k) => k, (v) => 0);

        foreach (var activity in guardsAsleepByMinute)
        {
            foreach (int guard in activity.Value.Where((p) => p is not 0))
            {
                sleepinessPerGuard[guard]++;
            }
        }

        int sleepiestGuard = sleepinessPerGuard
                             .OrderByDescending((p) => p.Value)
                             .Select((p) => p.Key)
                             .First();

        var minutesAsleepForSleepiestGuard = new Dictionary <int, int>();
        var sleepiestGuardsByMinute        = new Dictionary <int, Dictionary <int, int> >();

        foreach (var pair in guardsAsleepByMinute)
        {
            for (int i = 0; i < pair.Value.Length; i++)
            {
                int guard = pair.Value[i];

                if (guard == 0)
                {
                    continue;
                }

                bool isSleepiest = guard == sleepiestGuard;

                if (isSleepiest)
                {
                    minutesAsleepForSleepiestGuard.AddOrIncrement(i, 0);
                }

                sleepiestGuardsByMinute.GetOrAdd(i).AddOrIncrement(guard, 0);
            }
        }

        int sleepiestMinute = minutesAsleepForSleepiestGuard
                              .OrderByDescending((p) => p.Value)
                              .Select((p) => p.Key)
                              .First();

        int minuteGuard = sleepiestGuardsByMinute
                          .OrderByDescending((p) => p.Value.Values.Max())
                          .Select((p) => p.Key * p.Value.OrderByDescending((r) => r.Value).Select((r) => r.Key).First())
                          .First();

        int guardMinute = sleepiestGuard * sleepiestMinute;

        return(guardMinute, minuteGuard);
    }