Created
December 2, 2012 22:15
-
-
Save simonkro/4191303 to your computer and use it in GitHub Desktop.
Ruby Quiz Solution
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
def roman_to_arabic | |
{'M' => 1000, 'CM' => 900, 'D' => 500, 'CD' => 400, | |
'C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40, | |
'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, | |
'I' => 1} | |
end | |
def to_roman n | |
roman_to_arabic.map do |roman, arabic| | |
i, n = n.divmod(arabic) | |
roman * i | |
end.join | |
end | |
def from_roman n | |
roman_to_arabic.values_at( | |
*n.scan(/CM|CD|XC|XL|IX|IV|./) | |
).reduce(:+) | |
end | |
def convert n | |
n =~ /\d/ ? to_roman(n.to_i) : from_roman(n) | |
end | |
ARGF.each_line {|l| puts convert(l)} if $0 == __FILE__ |
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
require 'test/unit' | |
require './roman' | |
class RomanTest < Test::Unit::TestCase | |
def test_I_is_1 | |
assert(from_roman("I") == 1) | |
end | |
def test_IV_is_4 | |
assert(from_roman("IV") == 4) | |
end | |
def test_VIII_is_8 | |
assert(from_roman("VIII") == 8) | |
end | |
def test_CCXCI_is_291 | |
assert(from_roman("CCXCI") == 291) | |
end | |
def test_MCMXCIX_is_1999 | |
assert(from_roman("MCMXCIX") == 1999) | |
end | |
def test_XXXVIII_is_38 | |
assert(from_roman("XXXVIII") == 38) | |
end | |
def test_XXIX_is_29 | |
assert(from_roman("XXIX") == 29) | |
end | |
def test_1_is_I | |
assert(to_roman(1) == "I") | |
end | |
def test_2_is_II | |
assert(to_roman(2) == "II") | |
end | |
def test_4_is_IV | |
assert(to_roman(4) == "IV") | |
end | |
def test_45_is_XLV | |
assert(to_roman(45) == "XLV") | |
end | |
def test_291_is_CCXCI | |
assert(to_roman(291) == "CCXCI") | |
end | |
def test_1999_is_MCMXCIX | |
assert(to_roman(1999) == "MCMXCIX") | |
end | |
def test_38_is_XXXVIII | |
assert(to_roman(38) == "XXXVIII") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment