From: Gennady Bystritsky Date: 2009-11-11T10:23:02+09:00 Subject: Re: Roman Numerals (Arrgh!) Well, considering that you at least started thinking on the problem and did some research, I am going to give you a solution. With a twist, of course -- it uses "advanced" array's method inject() that I wouldn't dare showing to your professors without being able to explain it. So work through it and simplify for your homework: NOTE: The following code does not take into account the "subtraction rule". $numerals = [[1000, "M"], [500, "D"], [100, "C"], [50, "L"], [10, "X"], [5, "V"], [1, "I"]] def roman_numeral(number) $numerals.inject(["", number]) { |result, numeral| [ result[0] + numeral[1] * (result[1] / numeral[0]), number % numeral[0] ] }.first end p roman_numeral(1) # => "I" p roman_numeral(4) # => "IIII" p roman_numeral(5) # => "V" p roman_numeral(6) # => "VI" p roman_numeral(10) # => "X" p roman_numeral(19) # => "XVIIII" p roman_numeral(21) # => "XXI" p roman_numeral(180) # => "CLXXX" p roman_numeral(949) # => "DCCCCXXXXVIIII" On Nov 10, 2009, at 3:56 PM, Rick Barrett wrote: > I have a homework assignment where I have to convert an inputted integer > into Roman Numerals. I was doing fine building upon the previous steps > until the arrays came in. We have to use the format/guidelines the > professors give us or we get points counted off. I've looked at so many > ways to do this program through Google, but none of the examples I've > seen are even close to what the professor wrote out. > > Basically, in my code I have to use the array $numerals and create pairs > with the integer and its corresponding Roman Numeral. > > What I can't figure out how to do is say something like... > > For each 10 of the inputted number put an X > > I was thinking something along the lines of dividing the inputted number > by the decimal and taking the remaining integer and multiplying the > Roman Numeral by that integer. > > Like 30/10 = 3 so "X" * 3 would print out XXX > > But I have no idea how to do that with the $numerals array. > > How do I get my program to say divide the inputted number by the decimal > part of the pair and then give the numeral part that many times? > > def roman_numeral(number) > > $numerals = [[10, "X"], > [5, "V"], > [1, "I"]] > > result = "" > > $numerals.each() do |decimal, numeral| > > > result = new_variable > end > > return result > end > > puts "Enter a number to be converted to Roman Numerals." > my_number = gets().chomp().to_i() > puts roman_numeral(my_number) > -- > Posted via http://www.ruby-forum.com/. > Sincerely, Gennady Bystritsky Software Developer 4 Quest Software, Inc. Aliso Viejo, CA