Created
December 8, 2012 01:40
-
-
Save feltnerm/4238087 to your computer and use it in GitHub Desktop.
a simple Roman number calculator. It is to read a Roman number, an operator (+, -, /, or *), and a second Roman number. It then shows the calculation using Arabic numbers and prints the result as a Roman number.
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
#!/usr/bin/env ruby | |
# AUTHOR: Mark Feltner | |
OPERANDS = { | |
"I" => 1, | |
"V" => 5, | |
"X" => 10, | |
"L" => 50, | |
"C" => 100, | |
"D" => 500, | |
"M" => 1000 | |
} | |
def to_arabic(roman_int) | |
value = 0 | |
roman_int.chars { |c| value+=OPERANDS[c] } | |
return value | |
end | |
def to_roman(arabic_int) | |
roman_str = "" | |
if arabic_int < 0 | |
arabic_int = arabic_int.abs | |
roman_str += '-' | |
elsif arabic_int == 0 | |
return "zero" | |
end | |
for k,v in OPERANDS.invert.sort.reverse | |
if (x = arabic_int / k)>0 | |
arabic_int = arabic_int % k | |
roman_str += OPERANDS.invert[k] * x | |
end | |
end | |
return roman_str | |
end | |
def process_expression | |
n = 1 | |
while (line = gets) | |
expression = line.split " " | |
operand1 = to_arabic(expression[0]) | |
operand2 = to_arabic(expression[2]) | |
operator = expression[1] | |
arabic_result = 0 | |
if operator == '+' | |
arabic_result = operand1 + operand2 | |
elsif operator == '-' | |
arabic_result = operand1 - operand2 | |
elsif operator == '*' | |
arabic_result = operand1 * operand2 | |
elsif operator == '/' | |
arabic_result = operand1 / operand2 | |
end | |
roman_result = to_roman(arabic_result) | |
puts "#{operand1} #{operator} #{operand2} = #{arabic_result} = #{roman_result}" | |
end | |
end | |
process_expression | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment