Roman numerals/Decode

From Rosetta Code
Revision as of 18:07, 13 May 2011 by rosettacode>Mwn3d (Added untested Prolog (no runtime env available))
Roman numerals/Decode is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Create a function taking a Roman numeral as its argument and returning the value of the numeral. You don't need to validate the form of the Roman numeral.

Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost digit and skipping any 0s. So 1990 is rendered "MCMXC" (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered "MMVIII" (2000 = MM, 8 = VIII). The Roman numeral for 1666, "MDCLXVI", uses each letter in descending order.

Icon and Unicon

<lang Icon>link numbers

procedure main() every R := "MCMXC"|"MDCLXVI"|"MMVIII" do

  write(R, " = ",unroman(R))

end</lang>

numbers.icn provides unroman

The code for this procedure is copied below:<lang Icon>procedure unroman(s) #: convert Roman numeral to integer

  local nbr,lastVal,val
  nbr := lastVal := 0
  s ? {
     while val := case map(move(1)) of {

"m": 1000 "d": 500 "c": 100 "l": 50 "x": 10 "v": 5 "i": 1 } do { nbr +:= if val <= lastVal then val else val - 2 * lastVal lastVal := val }

     }
  return nbr

end</lang>

Output:

MCMXC = 1990
MDCLXVI = 1666
MMVIII = 2008

J

<lang j>rom2d=: [: (+/ .* _1^ 0,~ 2</\ ]) 1 5 10 50 100 500 1000 {~ 'IVXLCDM'&i.</lang>

Example use:

<lang j> rom2d 'MCMXC' 1990

  rom2d 'MDCLXVI'

1666

  rom2d 'MMVIII'

2008</lang>

Java

<lang java>public class Roman{ private static int decodeSingle(char letter){ switch(letter){ case 'M': return 1000; case 'D': return 500; case 'C': return 100; case 'L': return 50; case 'X': return 10; case 'V': return 5; case 'I': return 1; default: return 0; } } public static int decode(String roman){ int result = 0; String uRoman = roman.toUpperCase(); //case-insensitive for(int i = 0;i < uRoman.length() - 1;i++){//loop over all but the last character //if this character has a lower value than the next character if(decodeSingle(uRoman.charAt(i)) < decodeSingle(uRoman.charAt(i + 1))){ //subtract it result -= decodeSingle(uRoman.charAt(i)); }else{ //add it result += decodeSingle(uRoman.charAt(i)); } } //decode the last character, which is always added result += decodeSingle(uRoman.charAt(uRoman.length()-1)); return result; }

public static void main(String[] args){ System.out.println(decode("MCMXC")); //1990 System.out.println(decode("MMVIII")); //2008 System.out.println(decode("MDCLXVI")); //1666 } }</lang> Output:

1990
2008
1666

Prolog

This example is untested. Please check that it's correct, debug it as necessary, and remove this message.


Works with: SWI Prolog

<lang prolog>char_to_num('M', 1000). char_to_num('D', 500). char_to_num('C', 100). char_to_num('L', 50). char_to_num('X', 10). char_to_num('V', 5). char_to_num('I', 1). char_to_num(_, 0).

unroman(, 0).

unroman(Roman, X) :- string_length(Roman, Length), RestLen is Length - 1, NextLen is Length - 2, sub_string(Roman, 1, 1, RestLen, First), sub_string(Roman, 2, 1, NextLen, Next), sub_string(Roman, 2, RestLen, 0, Rest), char_to_num(First, FirstNum), char_to_num(Next, NextNum), FirstNum >= NextNum, unroman(Rest, RestNum), X is RestNum + FirstNum.

unroman(Roman, X) :- string_length(Roman, Length), RestLen is Length - 1, NextLen is Length - 2, sub_string(Roman, 1, 1, RestLen, First), sub_string(Roman, 2, 1, NextLen, Next), sub_string(Roman, 2, RestLen, 0, Rest), char_to_num(First, FirstNum), char_to_num(Next, NextNum), FirstNum < NextNum, unroman(Rest, RestNum), X is RestNum - FirstNum.</lang>

Python

<lang python>_rdecode = dict(zip('MDCLXVI', (1000, 500, 100, 50, 10, 5, 1)))

def decode( roman ):

   result = 0
   for r, r1 in zip(roman, roman[1:]):
       rd, rd1 = _rdecode[r], _rdecode[r1]
       result += -rd if rd < rd1 else rd
   return result + _rdecode[roman[-1]]

if __name__ == '__main__':

   for r in 'MCMXC MMVIII MDCLXVI'.split():
       print( r, decode(r) )</lang>
Sample output
MCMXC 1990
MMVIII 2008
MDCLXVI 1666

Tcl

As long as we assume that we have a valid roman number, this is most easily done by transforming the number into a sum and evaluating the expression: <lang tcl>proc fromRoman rnum {

   set map {M 1000+ CM 900+ D 500+ CD 400+ C 100+ XC 90+ L 50+ XL 40+ X 10+ IX 9+ V 5+ IV 4+ I 1+}
   expr [string map $map $rnum]0}

}</lang> Demonstrating: <lang tcl>foreach r {MCMXC MDCLXVI MMVIII} {

   puts "$r\t-> [fromRoman $r]"

}</lang> Output:

MCMXC	-> 1990
MDCLXVI	-> 1666
MMVIII	-> 2008

Zsh

<lang zsh>function parseroman () {

 local max=0 sum i j
 local -A conv
 conv=(I 1 V 5 X 10 L 50 C 100 D 500 M 1000)
 for j in ${(Oas::)1}; do
   i=conv[$j]
   if (( i >= max )); then
     (( sum+=i ))
     (( max=i ))
   else
     (( sum-=i ))
   fi
 done
 echo $sum

}</lang>