-
-
Save sidazhang/7112033 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def classic_roman(int) | |
# initialise variable | |
num = int | |
num = num.to_f | |
output = [] | |
# initialise keys | |
numeral_to_value = { | |
1 => "I", | |
5 => "V", | |
10 => "X", | |
50 => "L", | |
100 => "C", | |
500 => "D", | |
1000 => "M" | |
} | |
order = numeral_to_value.map do |k,v| | |
k | |
end | |
order = order.sort.reverse | |
# produce each letter methodically | |
order.each do |i| | |
x = (num / i).floor.to_i | |
x.times do | |
output.push(numeral_to_value[i]) | |
end | |
num = num - x*i | |
end | |
#return value | |
return output.join | |
end | |
#modern_roman will simply take classic_roman and find and replace any term repeated four times | |
def modern_roman(int) | |
#initialise keys | |
#wash 1 | |
replace_key1 = { | |
'IIII' => 'IV', | |
'XXXX' => 'XL', | |
'CCCC' => 'CD' | |
} | |
#wash 2 | |
replace_key2 = { | |
'VIV' => 'IX', | |
'LXL' => 'XC', | |
'DCD' => 'CM' | |
} | |
#initialise classic roman string to transform | |
output = classic_roman(int) | |
#execute wash 1 | |
replace_key1.each do |k,v| | |
until output.index(k) == nil | |
output = output.gsub(k,v) | |
end | |
end | |
#execute wash 2 | |
replace_key2.each do |k,v| | |
until output.index(k) == nil | |
output = output.gsub(k,v) | |
end | |
end | |
#return output | |
return output | |
end | |
#test methods | |
4000.times do |j| | |
puts j | |
puts classic_roman(j) | |
puts modern_roman(j) | |
puts "---" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment