Skip to content

Commit

Permalink
Refactored to_roman to use substraction strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
invadersmustdie committed Dec 26, 2011
1 parent e1c721f commit d315e02
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 13 deletions.
30 changes: 17 additions & 13 deletions lib/arrabiata.rb
Expand Up @@ -4,13 +4,19 @@ class NoZeroInRomanNumbers < ArrabiataError; end
class UnknownRomanNumberError < ArrabiataError; end

CONVERSION = {
"M" => 1000,
"D" => 500,
"C" => 100,
"L" => 50,
"X" => 10,
"V" => 5,
"I" => 1
"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
}

def self.to_roman(n)
Expand All @@ -19,12 +25,10 @@ def self.to_roman(n)

result = ""

# NOTE: this version doesn't yet respects the subtractive principle
CONVERSION.sort_by { |d| d.last }.reverse.each do |k|
x = n / k.last
if x != 0
result << k.first * x
n = n - x * k.last
CONVERSION.sort_by { |d| d.last }.reverse.each do |roman, arabic|
while(n >= arabic) do
result << roman
n -= arabic
end
end

Expand Down
16 changes: 16 additions & 0 deletions spec/arrabiata_to_roman_spec.rb
Expand Up @@ -32,4 +32,20 @@
it "should convert 2855 to MMDCCCLV" do
Arrabiata.to_roman(2855).should == "MMDCCCLV"
end

it "should convert 79 to LXXIX" do
Arrabiata.to_roman(79).should == "LXXIX"
end

it "should convert 4 to IV" do
Arrabiata.to_roman(4).should == "IV"
end

it "should convert 19 to XIX" do
Arrabiata.to_roman(19).should == "XIX"
end

it "should convert 8759 to MMMMMMMMDCCLIX" do
Arrabiata.to_roman(8759).should == "MMMMMMMMDCCLIX"
end
end

0 comments on commit d315e02

Please sign in to comment.