diff --git a/bin/calculator b/bin/calculator index 724e06b..e961416 100755 --- a/bin/calculator +++ b/bin/calculator @@ -27,5 +27,5 @@ class_b = ARGV[3] number_b = ARGV[4] mode = ARGV[5].to_s || 'arabic' -first = class_a.constantize.new(number_a) -puts first.send(operator, class_b.constantize.new(number_b)) +first = class_a.constantize.new(number_a, mode) +puts first.send(operator, class_b.constantize.new(number_b, mode)) diff --git a/lib/converter.rb b/lib/sa_converter.rb similarity index 54% rename from lib/converter.rb rename to lib/sa_converter.rb index dd68760..6aa3c27 100644 --- a/lib/converter.rb +++ b/lib/sa_converter.rb @@ -1,6 +1,6 @@ class SAConverter - INT_VAL = { + INT_VAL = { 'I' => 1, 'V' => 5, 'X' => 10, @@ -10,12 +10,26 @@ class SAConverter 'M' => 1000 } - def initialize(roman) + ROMAN_VAL = INT_VAL.invert + + SPECIAL = { + 4 => 'IV', + 9 => 'IX', + 40 => 'XL', + 90 => 'XC', + 400 => 'CD', + 900 => 'CM' + } + + + def initialize(roman, mode='arabic') @roman = roman + @mode = mode end def +(other) - self.to_i + other.to_i + result = self.to_i + other.to_i + @mode == 'arabic' ? result : to_roman(result) end def -(other) @@ -30,6 +44,26 @@ def /(other) self.to_i / other.to_i end + def lookup + @lookup ||= Hash[(ROMAN_VAL.merge SPECIAL).sort.reverse] + end + + def to_roman(val) + result = '' + while val > 0 + k, v = *find_largest(val) + val -= k + result << v + end + result + end + + def find_largest(val) + lookup.each do |k, v| + return [k,v] if k <= val + end + end + # Use this method to convert roman numbers to arabic # # Don't you dare cheat on spec!!! diff --git a/spec/lib/converter_spec.rb b/spec/lib/converter_spec.rb index 3a5682d..0b59b49 100644 --- a/spec/lib/converter_spec.rb +++ b/spec/lib/converter_spec.rb @@ -32,7 +32,7 @@ roman = conversion[1] it "converts #{roman} to #{arabic}" do - expect(described_class.convert(roman)).to eq arabic + expect(described_class.new(roman).to_i).to eq arabic end end end