diff --git a/.gitignore b/.gitignore index 5e1422c..1d6eb45 100644 --- a/.gitignore +++ b/.gitignore @@ -48,3 +48,6 @@ build-iPhoneSimulator/ # unless supporting rvm < 1.11.0 or doing something fancy, ignore this: .rvmrc + +*.sublime-project +*.sublime-workspace \ No newline at end of file diff --git a/lib/roman_numeral.rb b/lib/roman_numeral.rb index e4b6200..12fc553 100644 --- a/lib/roman_numeral.rb +++ b/lib/roman_numeral.rb @@ -32,8 +32,12 @@ def initialize( numeral_string ) end def self.romanize(decimal) - reverse_hashroman = HASHROMAN.invert - + roman="" + HASHROMAN.sort_by {|num, val| val }.reverse.each{|num, val| + roman+=num.to_s*(decimal/val).floor # It's a symbol at this point, + decimal-=(decimal/val).floor*val + } + roman end def self.decimal_value(numerical_string) @@ -53,7 +57,17 @@ def +( other_roman ) end def -( numeral_string ) - "MCMXCVI" + dec_num = decimal_val - numeral_string.decimal_val + dec_num >0 ? RomanNumeral.romanize(dec_num) : "-" + RomanNumeral.romanize(dec_num.abs) end -end + def *( other_roman ) + dec_num = other_roman.decimal_val * decimal_val + RomanNumeral.romanize(dec_num) + end + + def /( numeral_string ) + dec_num = (decimal_val / numeral_string.decimal_val).floor + dec_num >0 ? RomanNumeral.romanize(dec_num) : "-" + RomanNumeral.romanize(dec_num.abs) + end +end \ No newline at end of file diff --git a/spec/roman_numeral_spec.rb b/spec/roman_numeral_spec.rb index 74d6a85..19a2f46 100644 --- a/spec/roman_numeral_spec.rb +++ b/spec/roman_numeral_spec.rb @@ -1,14 +1,24 @@ require 'spec_helper' require 'roman_numeral' - describe RomanNumeral do - it 'should compute simple arithmatic' do - @reports << Benchmark.measure do + # 1996 plus 14 equals 2010 expect( RomanNumeral.new( 'MCMXCVI' ) + RomanNumeral.new( 'XIV' ) ).to eq('MMX') - expect( RomanNumeral.new( 'MMX' ) + RomanNumeral.new( 'XIV' ) ).to eq('MCMXCVI') - end - end -end + # 2010 minus 14 equals 1996 + expect( RomanNumeral.new( 'MMX' ) - RomanNumeral.new( 'XIV' ) ).to eq('MCMXCVI') + + # 1996 minus 1996 equals -14 + expect( RomanNumeral.new( 'MCMXCVI' ) - RomanNumeral.new( 'MMX' ) ).to eq('-XIV') + + # 23 times 11 equals 253 + expect( RomanNumeral.new( 'XXIII' ) * RomanNumeral.new( 'XI' ) ).to eq('CCLIII') + + # 253 divided by 11 equals 23 + expect( RomanNumeral.new( 'CCLIII' ) / RomanNumeral.new( 'XI' ) ).to eq('XXIII') + + # 100 divided by 33 equals 3. The romans had a complicated fraction system, we're not going there. + expect( RomanNumeral.new( 'C' ) / RomanNumeral.new( 'XXXIII' ) ).to eq('III') + end +end \ No newline at end of file