Decodificatore di numeri romani: Ruby
Sep 10 2020
Bene, ho lavorato a questa sfida di programmazione per un bel po 'di tempo e credo che sia ufficialmente il momento per me di alzare la bandiera. Aiuto!
Il mio compito è creare una funzione che prenda un numero romano come argomento e restituisca il suo valore come numero intero decimale numerico.
Finora ho creato con successo un hash mappando i numeri ai suoi valori numerici. Ho anche creato un array vuoto roman_noper passare la coppia chiave / valore.
Quello con cui sto lottando è scrivere l'espressione. Di seguito è riportato il codice completo:
def solution(roman)
# take a value of a roman numeral
roman_numeral =
{
1000 => "M",
900 => "CM",
500 => "D",
400 => "CD",
100 => "C",
90 => "XC",
50 => "L",
40 => "XL",
10 => "X",
9 => "IX",
5 => "V",
4 => "IV",
1 => "I"
}
roman_no = Array.new
roman_numeral.each do | key, value |
while
"#{roman}" >= "#{key}"
+= roman_no
"#{roman}" -= "#{key}"
end
return roman_no
solution('XXI')
Come posso scrivere un argomento che prenda il valore da roman_numerale restituisca la sua parte contatore numero?
per esempio:
solution('XXI') # should return 21
Risposte
3 max Sep 10 2020 at 13:15
def solution(roman)
mapping = {
"M"=>1000,
"D"=>500,
"C"=>100,
"L"=>50,
"X"=>10,
"V"=>5,
"I"=>1
}
# split string into characters
roman.chars.map do |l|
mapping[l] # replace character with integer value
end
.compact # removes potential nils caused by invalid chars
# Splits array into chunks so that we can handle numerals such as IIX
.chunk_while do |i,j|
i <= j #
end
# each chunk will be an array like [10, 10, 100] or [1, 1, 1, 1]
.map do |chunk|
if chunk.first < chunk.last
chunk.reverse.inject(:-) # handles numerals such as IIX with subtraction
else
chunk.sum # chunk is just a list of numerals such as III
end
end
.sum # sums everything up
end