Roman numerals/Decode: Difference between revisions

From Rosetta Code
Content added Content deleted
(add parsing roman numerals draft task, and implementation in zsh)
 
(J)
Line 4: Line 4:
Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: MDCLXVI.
Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: MDCLXVI.


=={{header|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>


=={{header|Zsh}}==
=={{header|Zsh}}==

Revision as of 20:55, 9 May 2011

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 parameter and returning the value of the numeral.

Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: MDCLXVI.

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>

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>