예제 #1
0
        public static string ToRoman(this int number)
        {
            var freq = new FrequencyCounter <string>();

            foreach (var mapping in _base10Mappings.OrderByDescending(m => m.Item2))
            {
                if (number < 1)
                {
                    break;
                }

                var result = number.DivideBy(mapping.Item2);
                number = result.Remainder;

                freq[mapping.Item1] = result.Quotient;
            }

            var output = new StringBuilder();

            foreach (var result in freq.GetItemFrequencies())
            {
                if (result.Count == 0)
                {
                    continue;
                }

                if (result.Count == 4 && _groupingLookup.ContainsKey(result.Item))
                {
                    output.Append(result.Item + _groupingLookup[result.Item]);
                    continue;
                }

                if (result.Count == 9 && _base10Mappings[_base10Mappings[result.Item] * 10] != null)
                {
                    output.Append(result.Item + _base10Mappings[_base10Mappings[result.Item] * 10]);
                    continue;
                }

                if (result.Count > 4 && _groupingLookup.ContainsKey(result.Item)) // 5, 6, 7, 8
                {
                    output.Append(_groupingLookup[result.Item] + result.Item.Repeat(result.Count - 5));
                    continue;
                }

                output.Append(result.Item.Repeat(result.Count));
            }

            return(output.ToString());
        }
예제 #2
0
        public static int GetRomanValue(this string roman)
        {
            var value = 0;

            foreach (var pair in _validSubractivePairs)
            {
                if (!roman.Contains(pair))
                {
                    continue;
                }

                value += GetSubtractivePairValue(pair);
                roman  = roman.Replace(pair, string.Empty);
            }

            var freq = new FrequencyCounter <string>();

            foreach (var mapping in _allMappings)
            {
                freq[mapping.Item1] = roman.Count(c => c.ToString() == mapping.Item1);
            }

            return(value + freq.GetItemFrequencies().Sum(result => result.Count * _allMappings[result.Item]));;
        }