Skip to content

Instantly share code, notes, and snippets.

@jsuchal
Last active August 29, 2015 14:03
Show Gist options
  • Save jsuchal/9e9e16a62125fc9e435b to your computer and use it in GitHub Desktop.
Save jsuchal/9e9e16a62125fc9e435b to your computer and use it in GitHub Desktop.
require 'minitest/autorun'
ARABIC_VALUES = {
'I' => 1, 'V' => 5, 'X' => 10, 'L' => 50, 'C' => 100, 'D' => 500, 'M' => 1000
}
def from_roman(roman)
chars = roman.chars << 'I'
chars.each_cons(2).inject(0) do |sum, (c1, c2)|
sum + (ARABIC_VALUES[c1] < ARABIC_VALUES[c2] ? -ARABIC_VALUES[c1] : ARABIC_VALUES[c1])
end
end
class RomanConversions < Minitest::Test
def test_from_roman
assert_equal 1, from_roman('I')
assert_equal 2, from_roman('II')
assert_equal 3, from_roman('III')
assert_equal 5, from_roman('V')
assert_equal 6, from_roman('VI')
assert_equal 8, from_roman('VIII')
assert_equal 10, from_roman('X')
assert_equal 30, from_roman('XXX')
assert_equal 24, from_roman('XXIV')
assert_equal 42, from_roman('XLII')
assert_equal 2014, from_roman('MMXIV')
assert_equal 1999, from_roman('MCMXCIX')
assert_equal 666, from_roman('DCLXVI')
assert_equal 444, from_roman('CDXLIV')
assert_equal 4, from_roman('IV')
assert_equal 9, from_roman('IX')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment