Created
April 10, 2013 06:32
-
-
Save szalansky/5352281 to your computer and use it in GitHub Desktop.
Roman numbers calculator (did as kata with Ruby and RSpec).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "rspec" | |
CONVERSIONS_FACTOR = [ | |
[100, "C"], [90, "XC"], [50, "L"], [40, "XL"], [10, "X"], [9, "IX"], [5, "V"], [4, "IV"], [1, "I"] | |
] | |
def conversion_factors_for number | |
CONVERSIONS_FACTOR.find { |arabic, _| arabic <= number } | |
end | |
def convert number | |
return "" if number.zero? | |
arabic, roman = conversion_factors_for number | |
roman + convert(number - arabic) | |
end | |
describe "Converting arabic numbers to roman numbers" do | |
context "Romans didn't have a 0" do | |
it "converts 0 to a blank string" do | |
expect(convert(0)).to eq("") | |
end | |
end | |
{ | |
1 => "I", | |
2 => "II", | |
4 => "IV", | |
5 => "V", | |
6 => "VI", | |
10 => "X", | |
16 => "XVI", | |
20 => "XX", | |
40 => "XL", | |
50 => "L", | |
100 => "C", | |
90 => "XC" | |
}.each_pair do |arabic, roman| | |
it "converts #{arabic} to #{roman}" do | |
expect(convert(arabic)).to eq(roman) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment