Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace Pairing
- {
- public static class RomanNumerals
- {
- // C# specification explicitly forbids explicit operator calls.
- // So build our own.
- private static int Add(int left, int right)
- {
- return left + right;
- }
- private static int Subtract(int left, int right)
- {
- return left - right;
- }
- private static int Convert(char romanNumeral)
- {
- switch (romanNumeral)
- {
- case 'I': return 1;
- case 'V': return 5;
- case 'X': return 10;
- case 'L': return 50;
- case 'C': return 100;
- case 'D': return 500;
- case 'M': return 1000;
- default: return 0;
- }
- }
- private static Func<int, int, int> DetermineAdditiveOrSubtractiveNotation(char left, char right)
- {
- const string numerals = "IVXLCDM";
- var rightDistance = numerals.IndexOf(right) - numerals.IndexOf(left);
- if (rightDistance == 1 || rightDistance == 2)
- {
- return Subtract;
- }
- else
- {
- return Add;
- }
- }
- private static (char, int) Sum((char, int) aggregate, char leftNumeral)
- {
- var (rightNumeral, total) = aggregate;
- var value = Convert(leftNumeral);
- var combine = DetermineAdditiveOrSubtractiveNotation(leftNumeral, rightNumeral);
- var newTotal = combine(total, value);
- return (leftNumeral, newTotal);
- }
- private static TAccumulator RightFold<T, TAccumulator>(this IEnumerable<T> source, TAccumulator seed, Func<TAccumulator, T, TAccumulator> func)
- {
- return source.Reverse().Aggregate(seed, func);
- }
- public static int Convert(string input)
- {
- var (_, result) = input.ToCharArray()
- .RightFold((' ', 0), Sum);
- return result;
- }
- }
- }
Add Comment
Please, Sign In to add comment