The old Google Groups will be going away soon, but your browser is incompatible with the new version.
This is a Usenet group - learn more
Message from discussion [QUIZ] Roman Numerals (#22)
The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet.
Your reply message has not been sent.
Your post was successful

From:
To:
Cc:
Followup To:
 Add Cc | Add Followup-to | Edit Subject
Subject:
 Validation: For verification purposes please type the characters you see in the picture below or the numbers you hear by clicking the accessibility icon.

More options Mar 7 2005, 1:35 pm
Newsgroups: comp.lang.ruby
From: Yannick Turgeon <nob...@nowhere.com>
Date: Mon, 07 Mar 2005 13:35:42 -0500
Local: Mon, Mar 7 2005 1:35 pm
Subject: Re: [SOLUTION][QUIZ] Roman Numerals (#22)
Here is my solution:

Being a 10-days-old Rubyist, I have to confest that I spent a lot of time
solving this problem and trying just for fun to make it more and more
concise at the price of clarity and no error handling. I've learned a lot
during the process. A very good problem to solve for beginners.

Yannick

--------------------
ARABIC = {"I" => 1, "IV" => 4, "V" => 5, "IX" => 9, "X" => 10, "XL" => 40,
"L" => 50, "XC" => 90, "C" => 100, "CD" => 400, "D" => 500, "CM" => 900,
"M" => 1000}
ROMAN = ARABIC.invert

def toInt(roman)
roman.reverse.split(//).inject(0) do |acc, letter|
acc += ARABIC[letter] * (acc > ARABIC[letter] * 3 ? -1 : 1)
end
end

def toRoman(number)
ARABIC.values.sort.reverse.inject("") do |acc, value|
mult, number = number.divmod(value)
acc << ROMAN[value] * mult
end
end

STDIN.readlines.each{|line| line.chomp!; print line, " = ", line.to_i > 0 ?
toRoman(line.to_i) : toInt(line), "\n"}
-------------------

Or Object Oriented:
-------------------
ARABIC = {"I" => 1, "IV" => 4, "V" => 5, "IX" => 9, "X" => 10, "XL" => 40,
"L" => 50, "XC" => 90, "C" => 100, "CD" => 400, "D" => 500, "CM" => 900,
"M" => 1000}
ROMAN = ARABIC.invert

class String
def roman_to_i()
self.reverse.split(//).inject(0) do |acc, letter|
acc += ARABIC[letter] * (acc > ARABIC[letter] * 3 ? -1 : 1)
end
end
end

class Integer
def to_roman()
remainder = self
ARABIC.values.sort.reverse.inject("") do |acc, value|
mult, remainder = remainder.divmod(value)
acc << ROMAN[value] * mult
end
end
end

STDIN.readlines.each{|line| line.chomp!; print line, " = ", line.to_i > 0 ?
line.to_i.to_roman : line.roman_to_i, "\n"}

You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.

 Create a group - Google Groups - Google Home - Terms of Service - Privacy Policy ©2013 Google