-
-
Save pigullino1975/31209b2d2757269784932529b28d57e7 to your computer and use it in GitHub Desktop.
Roman Numerals converter in C#. Run as a console application from Visual Studio. The 'Romanise' function is where the magic happens.
This file contains 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; | |
namespace RomanNumerals | |
{ | |
class Program | |
{ | |
// Create rules in descending order | |
static Rule[] Rules = new Rule[] | |
{ | |
new Rule(1000, "M"), | |
new Rule(900, "CM"), | |
new Rule(500, "D"), | |
new Rule(400, "CD"), | |
new Rule(100, "C"), | |
new Rule(90, "XC"), | |
new Rule(50, "L"), | |
new Rule(40, "XL"), | |
new Rule(10, "X"), | |
new Rule(9, "IX"), | |
new Rule(5, "V"), | |
new Rule(4, "IV"), | |
new Rule(1, "I"), | |
}; | |
static void Main(string[] args) | |
{ | |
// Let the user convert numbers until they close the program | |
while (true) | |
{ | |
Console.WriteLine("Enter a positive integer:"); | |
int n; | |
if (Int32.TryParse(Console.ReadLine(), out n) && n > 0) | |
Console.WriteLine("{0} in roman numerals is:\t {1}", n, Romanise(n)); // Write out the result | |
else | |
Console.WriteLine("That's not a positive integer"); | |
} | |
} | |
private static string Romanise(int n) | |
{ | |
if (n == 0) return ""; // Recursion termination | |
foreach (var rule in Rules) // Rules are in descending order | |
if (rule.N <= n) | |
return rule.Symbol + Romanise(n - rule.N); // Recurse | |
// If this line is reached then n < 0 | |
throw new ArgumentOutOfRangeException("n must be greater than or equal to 0"); | |
} | |
// Represents a substitution rule for a roman-numerals like numerical system | |
// Number 'N' is equivilant to string 'Symbol' in the system. | |
class Rule | |
{ | |
public int N { get; set; } | |
public string Symbol { get; set; } | |
public Rule(int n, string symbol) | |
{ | |
N = n; | |
Symbol = symbol; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment