Skip to content

Instantly share code, notes, and snippets.

@georgepowell
Last active January 8, 2022 11:45
Show Gist options
  • Save georgepowell/c59988ee723382106a61 to your computer and use it in GitHub Desktop.
Save georgepowell/c59988ee723382106a61 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.
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