Created
March 8, 2018 17:49
-
-
Save GraemeBradbury/452fd211def5c3d6244c84c7ad094167 to your computer and use it in GitHub Desktop.
RomanNumerals Convert to int
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment