Guest User

Untitled

a guest
Mar 17th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace Pairing
  6. {
  7. public static class RomanNumerals
  8. {
  9. // C# specification explicitly forbids explicit operator calls.
  10. // So build our own.
  11. private static int Add(int left, int right)
  12. {
  13. return left + right;
  14. }
  15.  
  16. private static int Subtract(int left, int right)
  17. {
  18. return left - right;
  19. }
  20.  
  21. private static int Convert(char romanNumeral)
  22. {
  23. switch (romanNumeral)
  24. {
  25. case 'I': return 1;
  26. case 'V': return 5;
  27. case 'X': return 10;
  28. case 'L': return 50;
  29. case 'C': return 100;
  30. case 'D': return 500;
  31. case 'M': return 1000;
  32. default: return 0;
  33. }
  34. }
  35. private static Func<int, int, int> DetermineAdditiveOrSubtractiveNotation(char left, char right)
  36. {
  37. const string numerals = "IVXLCDM";
  38. var rightDistance = numerals.IndexOf(right) - numerals.IndexOf(left);
  39.  
  40. if (rightDistance == 1 || rightDistance == 2)
  41. {
  42. return Subtract;
  43. }
  44. else
  45. {
  46. return Add;
  47. }
  48. }
  49.  
  50. private static (char, int) Sum((char, int) aggregate, char leftNumeral)
  51. {
  52. var (rightNumeral, total) = aggregate;
  53. var value = Convert(leftNumeral);
  54. var combine = DetermineAdditiveOrSubtractiveNotation(leftNumeral, rightNumeral);
  55. var newTotal = combine(total, value);
  56. return (leftNumeral, newTotal);
  57. }
  58.  
  59. private static TAccumulator RightFold<T, TAccumulator>(this IEnumerable<T> source, TAccumulator seed, Func<TAccumulator, T, TAccumulator> func)
  60. {
  61. return source.Reverse().Aggregate(seed, func);
  62. }
  63.  
  64. public static int Convert(string input)
  65. {
  66. var (_, result) = input.ToCharArray()
  67. .RightFold((' ', 0), Sum);
  68.  
  69. return result;
  70. }
  71. }
  72. }
Add Comment
Please, Sign In to add comment