Skip to content

Instantly share code, notes, and snippets.

@justinko
Last active June 4, 2017 21:34
Show Gist options
  • Save justinko/ef778fc540ca3b6435eb70a9fc73ed32 to your computer and use it in GitHub Desktop.
Save justinko/ef778fc540ca3b6435eb70a9fc73ed32 to your computer and use it in GitHub Desktop.
Roman Numeral Calculator
require 'rspec/autorun'
class RomanNumeralCalculator
SYMBOL_MAPPING = {
1 => 'I',
4 => 'IV',
5 => 'V',
9 => 'IX',
10 => 'X',
40 => 'XL',
50 => 'L',
90 => 'XC',
100 => 'C',
400 => 'CD',
500 => 'D',
900 => 'CM',
1_000 => 'M'
}
def initialize(number)
@number = number
end
attr_reader :number
def convert_to_roman
symbols = ''
accumulator = 0
until accumulator == number
remainder = number - accumulator
value, symbol = tuple(accumulator.zero? ? number : remainder)
accumulator += value
symbols << symbol
end
symbols
end
private
def tuple(value)
value = SYMBOL_MAPPING.keys.select {|key| key <= value }.last
SYMBOL_MAPPING.find.with_index do |_, index|
index == SYMBOL_MAPPING.keys.index(value)
end
end
end
describe 'RomanNumeralCalculator' do
[
[ 1, 'I' ],
[ 2, 'II' ],
[ 3, 'III' ],
[ 4, 'IV' ],
[ 5, 'V' ],
[ 6, 'VI' ],
[ 8, 'VIII' ],
[ 15, 'XV' ],
[ 21, 'XXI' ],
[ 35, 'XXXV' ],
[ 44, 'XLIV' ],
[ 98, 'XCVIII' ]
].each do |arabic_numeral, roman_numeral|
it "returns #{roman_numeral} for #{arabic_numeral}" do
numeral = RomanNumeralCalculator.new(arabic_numeral)
expect(numeral.convert_to_roman).to eq(roman_numeral)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment