#!/usr/bin/env ruby -w # # "Modern" Roman numerals # "Learn to Program" by Chris Pine, p. 76 def roman_numeral n result = '' result << 'M' * (n / 1000) n = n % 1000 if n >= 900 result << 'CM' n = n - 900 end result << 'D' * (n / 500) n = n % 500 if n >= 400 result << 'CD' n = n - 400 end result << 'C' * (n / 100) n = n % 100 if n >= 90 result << 'XC' n = n - 90 end result << 'L' * (n / 50) n = n % 50 if n >= 40 result << 'XL' n = n - 40 end result << 'X' * (n / 10) n = n % 10 if n >= 9 result << 'IX' n = n - 9 end result << 'V' * (n / 5) n = n % 5 if n >= 4 result << 'IV' n = n - 4 end result << 'I' * n end test_values = [ ['I', 1], ['II', 2], ['III', 3], ['IV', 4], ['V', 5], ['VI', 6], ['VII', 7], ['VIII', 8], ['IX', 9], ['X', 10], ['XI', 11], ['XII', 12], ['XIII', 13], ['XIV', 14], ['XV', 15], ['XVI', 16], ['XVII', 17], ['XVIII', 18], ['XIX', 19], ['XX', 20], ['XXX', 30], ['XL', 40], ['L', 50], ['LX', 60], ['LXX', 70], ['LXXX', 80], ['XC', 90], ['XCIX', 99], ['C', 100], ['CC', 200], ['CD', 400], ['D', 500], ['CM', 900], ['M', 1000], ['MIX', 1009], ['MCMXLV', 1945], ['MCMXCIX', 1999], ['MM', 2000], ['MMM', 3000], ] success = true test_values.each do |roman, arabic| test = roman_numeral arabic if test == roman puts "PASS: #{arabic} is #{test}" else puts "ERROR: #{arabic} is #{test}, should be #{roman}" success = false end end exit unless success n = 0 while n <= 3000 puts "#{n}: " + roman_numeral(n) n = n + 1 end