From: Josef 'Jupp' SCHUGT Date: 2004-02-28T10:07:53+09:00 Subject: Arabic # -> Roman # (Was: TDD Roman Numeral tutorial in Ruby) Hi! Wrote a simple conversion tool. Takes one command line argument. Interpretes it as a decimal number. Prints roman number for it. Returns 1 on error, 0 on success. Conversion of single digits has two cases a) digit is 4 or 9. In this case append n1[i] followed by n5[i] if digit is 4 and by n1[i+1] if digit is 9. b) digit is neither 4 nor 9. In this case append n5[i] if digit is greater or equals 5. Then append d modulo 5 times n1[i]. As far as tables are concerned uses bare necessities - symbols need to be stored in any case. Converting tool to a function is left as an exercise :-> The algorithm is not new. It is a formal representation of what one does when manually writing roman numbers. It can easily be expanded to additional symbols by simply adding them to the lists. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #!/usr/bin/env ruby n1 = [ 'I', 'X', 'C', 'M' ] n5 = [ 'V', 'L', 'D', nil ] max = 0 n1.each_index { |i| max += 3 * 10 ** i } n5.each_index { |i| max += 5 * 10 ** i unless i.nil? } exit 1 if ARGV.length != 1 x = ARGV.first.to_i r = "" exit 1 if x > max or x < 1 (n5.length - 1).downto(0) { |i| d = x / 10 ** i x -= d * 10 ** i if d == 4 or d == 9 r << n1[i] + (d == 4 ? n5[i] : n1[i+1]) else if d >= 5 r << n5[i] d -= 5 end r << n1[i] * (d % 5) end } puts r exit 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Didn't find a simpler solution. Improvements are welcome. Josef 'Jupp' SCHUGT -- E-Mail: .--- ..- .--. .--. .--.-. --. -- -..- .-.-.- -.. . http://oss.erdfunkstelle.de/ruby/ - German comp.lang.ruby FAQ http://rubyforge.org/users/jupp/ - Ruby projects at Rubyforge