On 12/9/06, Christopher L. [email protected] wrote:

I =1 V =5 X = 10 L = 50

C = 100 D = 500 M = 1000

Suggestions on a soloution?

- skeleton (I’ll use test/unit, as it’s easier to check the results)

require ‘test/unit’

def to_roman(int)

#
here comes the code

end

class TestToRoman < Test::Unit::TestCase

#
check the base digits

def test_roman_digits

assert_equal ‘I’, to_roman(1)

assert_equal ‘V’, to_roman(5)

assert_equal ‘X’, to_roman(10)

assert_equal ‘L’, to_roman(50)

assert_equal ‘C’, to_roman(100)

assert_equal ‘D’, to_roman(500)

assert_equal ‘M’, to_roman(1000)

end

def test_roman_more

assert_equal ‘I’, to_roman(1)

assert_equal ‘II’, to_roman(2)

assert_equal ‘III’, to_roman(3)

assert_equal ‘IIII’, to_roman(4)

```
assert_equal 'VI', to_roman(6)
assert_equal 'VII', to_roman(7)
assert_equal 'VIII', to_roman(8)
assert_equal 'VIIII', to_roman(9)
assert_equal 'MDCCCCLXXXVIIII', to_roman(1989)
```

end

end

- to the actual solution:

(you’ll be creating the number left-to-right)

*find largest digit less than the number. subtract its value from the*

number, add the digit to the result. repeat until the digit is larger

than the remainder. if there’s anything left, choose the next digit.

in fact, the text between the stars is the simplest/most generic

algorithm. the following things are just an optimisation.

The actual ruby code I’ll leave to you. First do anything that works

(use the test above to check, and add your own ones), no matter how

ugly it is. Then post your code, and somebody (be it me or anybody

else) will suggest you improvements.

- a bit of rubyism:

instead of

def to_roman(int)

…

end

and calling as to_roman(123) you can extend the integers themselves:

class Integer

def to_roman

#
use self insted of int parameter

end

end

and call as 123.to_roman - it’s nicer.