Roman numerals/Encode: Difference between revisions
m
syntax highlighting fixup automation
m (→{{header|Tailspin}}: update to stricter typing) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 16:
{{trans|Python}}
<
V rnums = ‘M CM D CD C XC L XL X IX V IV I’.split(‘ ’)
Line 30:
1009, 1444, 1666, 1945, 1997, 1999, 2000, 2008, 2010, 2011, 2500, 3000, 3999]
L(val) test
print(val‘ - ’to_roman(val))</
=={{header|8080 Assembly}}==
<
jmp test
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Line 131:
dgtbufdef: db 5,0
dgtbuf: ds 6
romanbuf:</
=={{header|8086 Assembly}}==
===Main and Supporting Functions===
The main program and test values: 70,1776,2021,3999,4000
<
call EncodeRoman
mov si,offset StringRam
Line 164:
ReturnToDos ;macro that calls the int that exits dos</
The <code>EncodeRoman</code> routine:
<
EncodeRoman:
Line 340:
ror al,cl ;AX = 0X0Yh
pop cx
ret</
Macros used:
<
push ax
push bx
Line 362:
pop bx
pop ax
endm</
===Output===
{{out}}
Line 374:
=={{header|Action!}}==
<
CARD ARRAY arabic=[1000 900 500 400 100 90 50 40 10 9 5 4 1]
PTR ARRAY roman(13)
Line 413:
PrintF("%U=%S%E",data(i),r)
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Roman_numerals_encode.png Screenshot from Atari 8-bit computer]
Line 426:
=={{header|ActionScript}}==
<
var lookup:Object = {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};
var roman:String = "", i:String;
Line 440:
trace("2008 in roman is " + arabic2roman(2008));
trace("1666 in roman is " + arabic2roman(1666));
</syntaxhighlight>
{{out}}
<pre>1990 in roman is MCMXC
Line 447:
</pre>
And the reverse:
<
var romanArr:Array = roman.toUpperCase().split('');
var lookup:Object = {I:1, V:5, X:10, L:50, C:100, D:500, M:1000};
Line 459:
trace("MCMXC in arabic is " + roman2arabic("MCMXC"));
trace("MMVIII in arabic is " + roman2arabic("MMVIII"));
trace("MDCLXVI in arabic is " + roman2arabic("MDCLXVI"));</
{{out}}
<pre>MCMXC in arabic is 1990
Line 466:
=={{header|Ada}}==
<
procedure Roman_Numeral_Test is
Line 498:
Put_Line (To_Roman (25));
Put_Line (To_Roman (944));
end Roman_Numeral_Test;</
{{out}}
<pre>
Line 512:
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<
[]CHAR adjust roman = "CCXXmmccxxii";
[]INT arabic = (1000000, 500000, 100000, 50000, 10000, 5000, 1000, 500, 100, 50, 10, 5, 1);
Line 540:
print((val, " - ", arabic to roman(val), new line))
OD
)</
{{out}} (last example is manually wrapped):
<pre style="height:30ex;overflow:scroll">
Line 641:
{{works with|awtoc|any - tested with release [http://www.jampan.co.nz/~glyn/aw2c.tar.gz Mon Apr 27 14:25:27 NZST 2009]}}
<!-- This specimen was emailed to be by Glyn Webster > "Here's a Roman number procedure that would fit in:" -->
<
PROCEDURE ROMAN (INTEGER VALUE NUMBER; STRING(15) RESULT CHARACTERS; INTEGER RESULT LENGTH);
Line 691:
ROMAN(2009, S, I); WRITE(S, I);
ROMAN(405, S, I); WRITE(S, I);
END.</
{{out}}
<pre>
Line 703:
=={{header|APL}}==
{{works with|Dyalog APL}}
<
⍝ Digits and corresponding values
ds←((⊢≠⊃)⊆⊢)' M CM D CD C XC L XL X IX V IV I'
Line 712:
(d⊃ds),∇⍵-d⊃vs ⍝ While one exists, add it and subtract from number
}⍵
}</
{{out}}
Line 724:
{{Trans|Haskell}}
(mapAccumL version)
<
-- roman :: Int -> String
Line 860:
missing value
end if
end snd</
{{Out}}
<pre>{"MMXVI", "MCMXC", "MMVIII", "MM", "MDCLXVI"}</pre>
Line 866:
=={{header|Arturo}}==
{{trans|Nim}}
<
[50 "L"] [40 "XL"] [10 "X"] [9 "IX"] [5 "V"] [4 "IV"] [1 "I"])
Line 892:
1000 1009 1444 1666 1945 1997 1999 2000 2008 2010 2011 2500
3000 3999] 'n
-> print [n "->" toRoman n]</
{{out}}
Line 953:
=={{header|AutoHotkey}}==
{{trans|C++}}
<
stor(value)
Line 980:
}
Return result . "O"
}</
=={{header|Autolisp}}==
<syntaxhighlight lang="autolisp">
(defun c:roman() (romanNumber (getint "\n Enter number > "))
(defun romanNumber (n / uni dec hun tho nstr strlist nlist rom)
Line 1,008:
rom
)
</syntaxhighlight>
{{out}}
<pre>
Line 1,018:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f ROMAN_NUMERALS_ENCODE.AWK
BEGIN {
Line 1,045:
return(roman1000[v] roman100[w] roman10[x] roman1[y])
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,055:
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<
2 N = 2008: GOSUB 5: PRINT N" = "V$
3 N = 1666: GOSUB 5: PRINT N" = "V$;
Line 1,061:
5 V = N:V$ = "": FOR I = 0 TO 12: FOR L = 1 TO 0 STEP 0:A = VAL ( MID$ ("1E3900500400100+90+50+40+10+09+05+04+01",I * 3 + 1,3))
6 L = (V - A) > = 0:V$ = V$ + MID$ ("M.CMD.CDC.XCL.XLX.IXV.IVI",I * 2 + 1,(I - INT (I / 2) * 2 + 1) * L):V = V - A * L: NEXT L,I
7 RETURN</
==={{header|ASIC}}===
{{trans|DWScript}}
<
REM Roman numerals/Encode
DIM Weights(12)
Line 1,107:
ExitToRoman:
RETURN
</syntaxhighlight>
==={{header|Commodore BASIC}}===
{{works with|Commodore BASIC|7.0}}
C-128 version:
<
110 FOR I=0 TO 12
120 : READ RN$(I), NV(I)
Line 1,137:
330 : LOOP
340 : PRINT RN$;CHR$(13)
350 LOOP</
{{works with|Commodore BASIC|3.5}}
C-16/116/Plus-4 version (BASIC 3.5 has DO/LOOP but not BEGIN/BEND)
<
110 FOR I=0 TO 12
120 : READ RN$(I), NV(I)
Line 1,165:
330 : LOOP
340 : PRINT RN$;CHR$(13)
350 LOOP</
{{works with|Commodore BASIC|2.0}}
This version works on any Commodore, though the title banner should be adjusted to match the color and screen width of the particular machine.
<
110 FOR I=0 TO 12
120 : READ RN$(I), NV(I)
Line 1,194:
340 : PRINT RN$;CHR$(13)
350 GOTO 210
</syntaxhighlight>
The output is the same for all the above versions:
Line 1,215:
==={{header|FreeBASIC}}===
{{works with|FreeBASIC}}
<
DIM SHARED arabic(0 TO 12) AS Integer => {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }
DIM SHARED roman(0 TO 12) AS String*2 => {"M", "CM", "D","CD", "C","XC","L","XL","X","IX","V","IV","I"}
Line 1,236:
PRINT "1666 = "; toRoman(1666)
PRINT "3888 = "; toRoman(3888)
</syntaxhighlight>
{{out}}
Line 1,246:
==={{header|IS-BASIC}}===
<
110 DO
120 PRINT :INPUT PROMPT "Enter an arabic number: ":N
Line 1,269:
310 END DEF
320 DATA 1000,"M",900,"CM",500,"D",400,"CD",100,"C",90,"XC"
330 DATA 50,"L",40,"XL",10,"X",9,"IX",5,"V",4,"IV",1,"I"</
==={{header|Nascom BASIC}}===
{{trans|DWScript}}
{{works with|Nascom ROM BASIC|4.7}}
<
10 REM Roman numerals/Encode
20 DIM WEIGHTS(12),SYMBOLS$(12)
Line 1,303:
580 GOTO 520
590 RETURN
</syntaxhighlight>
{{out}}
<pre>
Line 1,312:
==={{header|ZX Spectrum Basic}}===
<
20 DATA 500,"D",400,"CD"
30 DATA 100,"C",90,"XC"
Line 1,328:
150 GO TO 120
160 NEXT I
170 PRINT VALUE;"=";V$</
==={{header|BaCon}}===
<
GLOBAL roman$[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }
Line 1,354:
PRINT toroman$(2008)
PRINT toroman$(1666)
</syntaxhighlight>
{{out}}
<pre>
Line 1,364:
=={{header|BASIC256}}==
{{works with|BASIC256 }}
<
print 1666+" = "+convert$(1666)
print 2008+" = "+convert$(2008)
Line 1,381:
next i
end function
</syntaxhighlight>
{{out}}
<pre>
Line 1,392:
=={{header|Batch File}}==
{{trans|BASIC}}
<
setlocal enabledelayedexpansion
Line 1,423:
set result=!result!!rom%a%!
set /a value-=!arab%a%!
goto add_val</
{{Out}}
<pre>2009 = MMIX
Line 1,430:
=={{header|BBC BASIC}}==
<
PRINT ;2012, FNroman(2012)
PRINT ;1666, FNroman(1666)
Line 1,447:
ENDWHILE
NEXT
= r$</
{{out}}
<pre>
Line 1,457:
=={{header|BCPL}}==
<
let toroman(n, v) = valof
Line 1,498:
show(3888)
show(2021)
$)</
{{out}}
<pre>1666 = MDCLXVI
Line 1,510:
Reads the number to convert from standard input. No range validation is performed.
<
4-v >5+#:/#<\55+%:5/\5%:
vv_$9+00g+5g\00g8+>5g\00
g>\20p>:10p00g \#v _20gv
> 2+ v^-1g01\g5+8<^ +9 _
IVXLCDM</
{{out}}
Line 1,523:
=={{header|BQN}}==
{{trans|APL}}
<
ds ← 1↓¨(¯1+`⊏⊸=)⊸⊔" I IV V IX X XL L XC C CD D CM M"
vs ← 1e3∾˜ ⥊1‿4‿5‿9×⌜˜10⋆↕3
Line 1,530:
(⊑⟜ds∾·𝕊𝕩-⊑⟜vs) 1-˜⊑vs⍋𝕩
}
}</
{{out|Example use}}
<syntaxhighlight lang="text"> ToRoman¨ 1990‿2008‿1666‿2021
⟨ "MCMXC" "MMVIII" "MDCLXVI" "MMXXI" ⟩</
=={{header|Bracmat}}==
<
= indian roman cifr tenfoldroman letter tenfold
. !arg:#?indian
Line 1,584:
)
)
);</
{{out}}
<pre>1990 MCMXC
Line 1,596:
===Naive solution===
This solution is a smart but does not return the number written as a string.
<
Line 1,620:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>Enter arabic number:
Line 1,629:
</pre>
===Not thread-safe===
<
#include <stdio.h>
Line 1,717:
return 0;
}</
{{Output}}
<pre>Write given numbers as Roman numerals.
Line 1,740:
=={{header|C sharp|C#}}==
<
class Program
{
Line 1,767:
}
}
}</
One-liner Mono REPL
<
Func<int, string> toRoman = (number) =>
new Dictionary<int, string>
Line 1,788:
{1, "I"}
}.Aggregate(new string('I', number), (m, _) => m.Replace(new string('I', _.Key), _.Value));
</syntaxhighlight>
{{out}}
Line 1,807:
=={{header|C++}}==
===C++ 98===
<
#include <string>
Line 1,847:
std::cout << to_roman(i) << std::endl;
}
}</
===C++ 11===
<
#include <string>
Line 1,881:
for (int i = 0; i < 2018; i++)
std::cout << i << " --> " << to_roman(i) << std::endl;
}</
=={{header|Ceylon}}==
<
class Numeral(shared Character char, shared Integer int) {}
Line 1,928:
assert (toRoman(1990) == "MCMXC");
assert (toRoman(2008) == "MMVIII");
}</
=={{header|Clojure}}==
The easiest way is to use the built-in cl-format function
<
(partial clojure.pprint/cl-format nil "~@R"))
Line 1,938:
;"CXXIII"
(arabic->roman 99)
;"XCIX"</
(sorted-map
1 "I", 4 "IV", 5 "V", 9 "IX",
Line 1,954:
(int->roman 1999)
; "MCMXCIX"</
An alternate implementation:
<syntaxhighlight lang="clojure">
(defn a2r [a]
(let [rv '(1000 500 100 50 10 5 1)
Line 1,976:
(and (< a v) (< a l)) (recur a (rest rv) (rest dv) r)
:else (recur (- a l) (rest rv) (rest dv) (str r (rm d) (rm v)))))))))
</syntaxhighlight>
Usage:
<syntaxhighlight lang="clojure">
(a2r 1666)
"MDCLXVI"
Line 1,986:
(map a2r [1000 1 389 45])
("M" "I" "CCCLXXXIX" "XLV")
</syntaxhighlight>
An alternate implementation:
<syntaxhighlight lang="clojure">
(def roman-map
(sorted-map-by >
Line 2,011:
(>= v e) (cons roman (a2r v n))
(< v e) (cons roman (a2r v (rest n))))))))
</syntaxhighlight>
Usage:
<syntaxhighlight lang="clojure">
(a2r 1666)
"MDCLXVI"
Line 2,021:
(map a2r [1000 1 389 45])
("M" "I" "CCCLXXXIX" "XLV")
</syntaxhighlight>
=={{header|CLU}}==
<
rep = null
Line 2,070:
stream$putl(po, int$unparse(test) || " = " || roman$encode(test))
end
end start_up</
{{out}}
<pre>1666 = MDCLXVI
Line 2,081:
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
IDENTIFICATION DIVISION.
PROGRAM-ID. TOROMAN.
Line 2,135:
end-perform
.
</syntaxhighlight>
{{out}} (input was supplied via STDIN)
<pre>
Line 2,155:
=={{header|CoffeeScript}}==
<
decimal_to_roman = (n) ->
# This should work for any positive integer, although it
Line 2,202:
else
console.log "error for #{decimal}: #{roman} is wrong"
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(format nil "~@R" n))</
=={{header|Cowgol}}==
<
include "argv.coh";
Line 2,267:
print(decimalToRoman(number as uint16, &buffer as [uint8]));
print_nl();
end loop;</
{{out}}
Line 2,277:
=={{header|D}}==
<
in {
assert(n < 5000);
Line 2,302:
}
void main() {}</
=={{header|Delphi}}==
{{trans|DWScript}}
<
{$APPTYPE CONSOLE}
Line 2,333:
Writeln(IntegerToRoman(2008)); // MMVIII
Writeln(IntegerToRoman(1666)); // MDCLXVI
end.</
=={{header|DWScript}}==
{{trans|D}}
<
const symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];
Line 2,356:
PrintLn(toRoman(455));
PrintLn(toRoman(3456));
PrintLn(toRoman(2488));</
=={{header|EasyLang}}==
<syntaxhighlight lang="text">values[] = [ 1000 900 500 400 100 90 50 40 10 9 5 4 1 ]
symbol$[] = [ "M" "CM" "D" "CD" "C" "XC" "L" "XL" "X" "IX" "V" "IV" "I" ]
func num2rom num . rom$ .
Line 2,376:
print r$
call num2rom 1666 r$
print r$</
=={{header|ECL}}==
<
SetWeights := [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
SetSymbols := ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
Line 2,403:
RomanEncode(1990 ); //MCMXC
RomanEncode(2008 ); //MMVIII
RomanEncode(1666); //MDCLXVI</
=={{header|Eiffel}}==
<
APPLICATION
Line 2,464:
Result := rnum
end
end</
=={{header|Ela}}==
{{trans|Haskell}}
<
digit x y z k =
Line 2,483:
| else = digit 'I' 'V' 'X' x
map (join "" << toRoman) [1999,25,944]</
{{out}}
Line 2,491:
{{trans|C#}}
ELENA 5.0 :
<
import system'routines;
import extensions;
Line 2,522:
console.printLine("2008 : ", 2008.toRoman());
console.printLine("1666 : ", 1666.toRoman())
}</
{{out}}
<pre>
Line 2,532:
=={{header|Elixir}}==
{{trans|Erlang}}
<
def encode(0), do: ''
def encode(x) when x >= 1000, do: [?M | encode(x - 1000)]
Line 2,548:
defp digit(8, x, y, _), do: [y, x, x, x]
defp digit(9, x, _, z), do: [x, z]
end</
'''Another:'''
{{trans|Ruby}}
<
@symbols [ {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'} ]
Line 2,561:
Enum.join(roman)
end
end</
'''Test:'''
<
IO.puts "#{n}: #{Roman_numeral.encode(n)}"
end)</
{{out}}
Line 2,576:
=={{header|Emacs Lisp}}==
<
"Translate from arabic number AN to roman number.
For example, (ar2ro 1666) returns (M D C L X V I)."
Line 2,592:
((>= AN 4) (cons 'I (cons 'V (ar2ro (- AN 4)))))
((>= AN 1) (cons 'I (ar2ro (- AN 1))))
((= AN 0) nil)))</
=={{header|Erlang}}==
{{trans|OCaml}}
<
-export([to_roman/1]).
Line 2,615:
digit(7, X, Y, _) -> [Y, X, X];
digit(8, X, Y, _) -> [Y, X, X, X];
digit(9, X, _, Z) -> [X, Z].</
sample:
Line 2,630:
Alternative:
<
-module( roman_numerals ).
Line 2,651:
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}].
</syntaxhighlight>
{{out}}
Line 2,664:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM ARAB2ROMAN
Line 2,690:
TOROMAN(3888->ANS$) PRINT("3888 = ";ANS$)
END PROGRAM
</syntaxhighlight>
=={{header|Euphoria}}==
{{trans|BASIC}}
<
constant roman = {"M", "CM", "D","CD", "C","XC","L","XL","X","IX","V","IV","I"}
Line 2,711:
printf(1,"%d = %s\n",{2009,toRoman(2009)})
printf(1,"%d = %s\n",{1666,toRoman(1666)})
printf(1,"%d = %s\n",{3888,toRoman(3888)})</
{{out}}
Line 2,723:
Excel can encode numbers in Roman forms in 5 successively concise forms.
These can be indicated from 0 to 4. Type in a cell:
<syntaxhighlight lang="excel">
=ROMAN(2013,0)
</syntaxhighlight>
It becomes:
<syntaxhighlight lang="text">
MMXIII
</syntaxhighlight>
=={{header|F_Sharp|F#}}==
<
1 -> x
| 2 -> x + x
Line 2,760:
|> List.map (fun n -> roman n)
|> List.iter (printfn "%s")
0</
{{out}}
<pre>MCMXC
Line 2,768:
=={{header|Factor}}==
A roman numeral library ships with Factor.
<
( scratchpad ) 3333 >roman .
"mmmcccxxxiii"</
Parts of the implementation:
<
{ "m" "cm" "d" "cd" "c" "xc" "l" "xl" "x" "ix" "v" "iv" "i" }
Line 2,789:
roman-values roman-digits [
[ /mod swap ] dip <repetition> concat
] 2map "" concat-as nip ;</
=={{header|FALSE}}==
<
[$999>][1000- "M"]#
$899> [ 900-"CM"]?
Line 2,805:
$ 4> [ 5- "V"]?
$ 3> [ 4-"IV"]?
[$ ][ 1- "I"]#%</
=={{header|Fan}}==
<syntaxhighlight lang="fan">**
** converts a number to its roman numeral representation
**
Line 2,845:
}
}</
=={{header|Forth}}==
<
\ these are ( numerals -- numerals )
: ,I dup c@ C, ; : ,V dup 1 + c@ C, ; : ,X dup 2 + c@ C, ;
Line 2,865:
1999 roman type \ MCMXCIX
25 roman type \ XXV
944 roman type \ CMXLIV</
Alternative implementation
<
does> swap cells + @ ;
Line 2,885:
create (roman) 16 chars allot
1999 (roman) >roman type cr</
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
implicit none
Line 2,923:
end function roman
end program roman_numerals</
{{out}}
Line 2,933:
=={{header|FreeBASIC}}==
<
Function romanEncode(n As Integer) As String
Line 2,963:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 2,973:
=={{header|FutureBasic}}==
<
local fn DecimaltoRoman( decimal as short ) as Str15
Line 3,008:
print " 33 = "; fn DecimaltoRoman( 33 )
HandleEvents</
Output:
Line 3,027:
If you see boxes in the code below, those are supposed to be the Unicode combining overline (U+0305) and look like {{overline|IVXLCDM}}. Or, if you see overstruck combinations of letters, that's a different font rendering problem. (If you need roman numerals > 3999 reliably, it might best to stick to chiseling them in stone...)
<
import "fmt"
Line 3,065:
}
}
}</
{{out}}
<pre>
Line 3,074:
=={{header|Golo}}==
<
----
This module takes a decimal integer and converts it to a Roman numeral.
Line 3,132:
println("2008 == MMVIII? " + (2008: encode() == "MMVIII"))
println("1666 == MDCLXVI? " + (1666: encode() == "MDCLXVI"))
}</
=={{header|Groovy}}==
<
def roman(arabic) {
Line 3,162:
assert roman(1666) == 'MDCLXVI'
assert roman(1990) == 'MCMXC'
assert roman(2008) == 'MMVIII'</
=={{header|Haskell}}==
Line 3,168:
With an explicit decimal digit representation list:
<
digit x y z k =
[[x], [x, x], [x, x, x], [x, y], [y], [y, x], [y, x, x], [y, x, x, x], [x, z]] !!
Line 3,190:
main :: IO ()
main = print $ toRoman <$> [1999, 25, 944]</
{{out}}
<pre>["MCMXCIX","XXV","CMXLIV"]</pre>
Line 3,196:
or, defining '''romanFromInt''' in terms of mapAccumL
<
import Data.List (mapAccumL)
import Data.Tuple (swap)
Line 3,213:
main :: IO ()
main = (putStrLn . unlines) (roman <$> [1666, 1990, 2008, 2016, 2018])</
{{Out}}
<pre>MDCLXVI
Line 3,223:
With the Roman patterns abstracted, and in a simple logic programming idiom:
<
module Main where
Line 3,283:
(if roman == expected then "PASS"
else ("FAIL, expected " ++ (show expected))) ++ ")"
</syntaxhighlight>
{{out}}
<pre>
Line 3,292:
=={{header|HicEst}}==
<
CALL RomanNumeral(1990, Roman) ! MCMXC
Line 3,313:
ENDDO
ENDDO
END</
=={{header|Icon}} and {{header|Unicon}}==
<
procedure main(arglist)
every x := !arglist do
write(commas(x), " -> ",roman(x)|"*** can't convert to Roman numerals ***")
end</
{{libheader|Icon Programming Library}}
[http://www.cs.arizona.edu/icon/library/src/procs/numbers.icn numbers.icn provides roman] as seen below and is based upon a James Gimple SNOBOL4 function.
<
local arabic, result
static equiv
Line 3,337:
result := map(result,"IVXLCDM","XLCDM**") || equiv[arabic + 1]
if find("*",result) then fail else return result
end</
{{out}}
Line 3,354:
INTERCAL outputs numbers as Roman numerals by default, so this is surprisingly trivial for a language that generally tries to make things as difficult as possible. Although you do still have to <i>input</i> the numbers as spelled out digitwise in all caps.
<
DO READ OUT .1
DO GIVE UP</
{{Out}}
Line 3,369:
{{trans|C#}}
<
nums := list(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
rum := list("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")
Line 3,386:
)
Roman numeral(1666) println</
=={{header|J}}==
<tt>rfd</tt> obtains Roman numerals from decimals.
<
C CC CCC CD D DC DCC DCCC CM
X XX XXX XL L LX LXX LXXX XC
Line 3,397:
)
rfd=: ('M' $~ <.@%&1000) , R1000 {::~ 1000&|</
Explanation: R1000's definition contains rows representing each of 10 different digits in the 100s, 10s and 1s column (the first entry in each row is blank -- each entry is preceded by a space). R1000 itself represents the first 1000 roman numerals (the cartesian product of these three rows of roman numeral "digits" which is constructed so that they are in numeric order. And the first entry -- zero -- is just blank). To convert a number to its roman numeral representation, we will separate the number into the integer part after dividing by 1000 (that's the number of 'M's we need) and the remainder after dividing by 1000 (which will be an index into R1000).
For example:<
MCCXXXIV
rfd 567
DLXVII
rfd 89
LXXXIX</
Derived from the [[j:Essays/Roman Numerals|J Wiki]]. Further examples of use will be found there.
Line 3,415:
The conversion function throws an IllegalArgumentException for non-positive numbers, since Java does not have unsigned primitives.
{{works with|Java|1.5+}}
<
enum Numeral {
Line 3,455:
}
}</
{{out}}
<pre>1999 = MCMXCIX
Line 3,465:
at RN.main(RN.java:38)</pre>
{{works with|Java|1.8+}}
<
import java.util.EnumSet;
import java.util.Collections;
Line 3,523:
LongStream.of(1999, 25, 944).forEach(RomanNumerals::test);
}
}</
{{out}}
<pre>1999 = MCMXCIX
Line 3,538:
{{trans|Tcl}}
<
map: [
1000, 'M', 900, 'CM', 500, 'D', 400, 'CD', 100, 'C', 90, 'XC',
Line 3,555:
}
roman.int_to_roman(1999); // "MCMXCIX"</
====Functional composition====
<
'use strict';
Line 3,607:
romanTranscription);
})();</
{{Out}}
<
===ES6===
Line 3,616:
{{Trans|Haskell}}
(mapAccumL version)
<
"use strict";
Line 3,693:
// MAIN --
return main();
})();</
{{Out}}
<pre>MDCLXVI
Line 3,703:
====Declarative====
<
return 'I'
.repeat(num)
Line 3,720:
}
console.log(toRoman(1666));</
{{Out}}
<syntaxhighlight lang
=={{header|jq}}==
Line 3,738:
===Easy-to-code version===
<
def romans:
[100000, "\u2188"],
Line 3,769:
| .n = .n - $i ) )
| .res
end ;</
'''Test Cases'''
<
"Decimal => Roman:",
(testcases[]
| " \(.) => \(to_roman_numeral)" )</
{{out}}
<pre>
Line 3,793:
==="Orders of Magnitude" version===
'''Translated from [[#Julia|Julia]]''' extended to 399,999
<
# Non-negative integer to Roman numeral up to 399,999
def to_roman_numeral:
Line 3,812:
| .rnum
end;
</syntaxhighlight>
=={{header|Jsish}}==
This covers both Encode (toRoman) and Decode (fromRoman).
<
var Roman = {
ord: ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'],
Line 3,872:
Roman.toRoman(1666) ==> MDCLXVI
=!EXPECTEND!=
*/</
{{out}}
Line 3,879:
=={{header|Julia}}==
<
function romanencode(n::Integer)
Line 3,912:
for n in testcases
@printf("%-4i => %s\n", n, romanencode(n))
end</
{{out}}
Line 3,933:
=={{header|Kotlin}}==
<
1000 to "M",
900 to "CM",
Line 3,968:
println(encode(1666))
println(encode(2008))
}</
{{out}}
Line 3,977:
</pre>
Alternatively:
<
fun digit(k: Int, unit: String, five: String, ten: String): String {
return when (k) {
Line 3,995:
else -> throw IllegalArgumentException("${this} not in range 0..3999")
}
}</
=={{header|Lasso}}==
<
// encode roman
define encodeRoman(num::integer)::string => {
Line 4,016:
'2008 in roman is '+encodeRoman(2008)
br
'1666 in roman is '+encodeRoman(1666)</
=={{header|LaTeX}}==
The macro <code>\Roman</code> is defined for uppercase roman numeral, accepting as ''argument'' a name of an existing counter.
<
\newcounter{currentyear}
\setcounter{currentyear}{\year}
\begin{document}
Anno Domini \Roman{currentyear}
\end{document}</
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
dim arabic( 12)
for i =0 to 12
Line 4,061:
toRoman$ =result$
end function
</syntaxhighlight>
<pre>
2009 MMIX
Line 4,069:
=={{header|LiveCode}}==
<
local roman,numArabic
put "M,CM,D,CD,C,XC,L,XL,X,IX,V,IV,I" into romans
Line 4,090:
end repeat
return cc
end repeatChar</
Examples
Line 4,099:
=={{header|Logo}}==
<
[1000 M] [900 CM] [500 D] [400 CD]
[ 100 C] [ 90 XC] [ 50 L] [ 40 XL]
Line 4,110:
if :n < first first :rules [output (roman :n bf :rules :acc)]
output (roman :n - first first :rules :rules word :acc last first :rules)
end</
{{works with|UCB Logo}}
<
to digit :d :numerals
Line 4,130:
print roman 1999 ; MCMXCIX
print roman 25 ; XXV
print roman 944 ; CMXLIV</
=={{header|LOLCODE}}==
<
I HAS A Romunz ITZ A BUKKIT
Romunz HAS A SRS 0 ITZ "M"
Line 4,182:
VISIBLE SMOOSH 1666 " = " I IZ Romunize YR 1666 MKAY MKAY
VISIBLE SMOOSH 3888 " = " I IZ Romunize YR 3888 MKAY MKAY
KTHXBYE</
{{Out}}
Line 4,190:
=={{header|LotusScript}}==
<
Function toRoman(value) As String
Dim arabic(12) As Integer
Line 4,235:
End Function
</syntaxhighlight>
=={{header|Lua}}==
<
{1000, "M"},
{900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"},
Line 4,253:
end
end
print()</
=={{header|M4}}==
<
`ifelse(eval($1>=900),1,`CM`'roman(eval($1-900))',
`ifelse(eval($1>=500),1,`D`'roman(eval($1-500))',
Line 4,270:
)')')')')')')')')')')')')dnl
dnl
roman(3675)</
{{out}}
Line 4,278:
=={{header|Maple}}==
<
1666 MDCLXVI
1990 MCMXC
2008 MMVIII</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
RomanNumeral is a built-in function in the Wolfram language. Examples:
<
RomanNumeral[99]
RomanNumeral[1337]
RomanNumeral[1666]
RomanNumeral[6889]</
gives back:
<pre>IV
Line 4,321:
=== roman.m ===
<syntaxhighlight lang="mercury">
:- module roman.
Line 4,374:
:- end_module roman.
</syntaxhighlight>
{{out}}
Line 4,400:
Another implementation using an algorithm inspired by [[#Erlang|the Erlang implementation]] could look like this:
<syntaxhighlight lang="mercury">
:- module roman2.
Line 4,449:
:- end_module roman2.
</syntaxhighlight>
This implementation calculates the value of the thousands, then the hundreds, then the tens, then the ones. In each case it uses the <code>digit/4</code> function and some tricks with unification to build the appropriate list of characters for the digit and multiplier being targeted.
Line 4,457:
=={{header|Microsoft Small Basic}}==
{{trans|DWScript}}
<
arabicNumeral = 1990
ConvertToRoman()
Line 4,505:
EndWhile
EndSub
</syntaxhighlight>
{{out}}
<pre>
Line 4,516:
{{trans|DWScript}}
{{works with|ADW Modula-2|any (Compile with the linker option ''Console Application'').}}
<
MODULE RomanNumeralsEncode;
Line 4,563:
ToRoman(3888, Numeral); WriteString(Numeral); WriteLn; (* MMMDCCCLXXXVIII *)
END RomanNumeralsEncode.
</syntaxhighlight>
{{out}}
<pre>
Line 4,572:
=={{header|MUMPS}}==
<
;Converts INPUT into a Roman numeral. INPUT must be an integer between 1 and 3999
;OUTPUT is the string to return
Line 4,585:
.FOR Q:CURRVAL<$PIECE(ROMANVAL,"^",I) SET OUTPUT=OUTPUT_$PIECE(ROMANNUM,"^",I),CURRVAL=CURRVAL-$PIECE(ROMANVAL,"^",I)
KILL I,CURRVAL
QUIT OUTPUT</
{{out}}
<pre>USER>W $$ROMAN^ROSETTA(1666)
Line 4,599:
Another variant
<
;return empty string if input parameter 'n' is not in 1-3999
Quit:(n'?1.4N)!(n'<4000)!'n ""
Line 4,609:
. Set x=$Translate(x,"IVX",$Piece("IVX~XLC~CDM~M","~",p-j+1))
. Set r=r_x
Quit r</
=={{header|Nim}}==
{{trans|Python}}
<
const nums = [(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"),
Line 4,630:
1000, 1009, 1444, 1666, 1945, 1997, 1999,
2000, 2008, 2010, 2011, 2500, 3000, 3999]:
echo ($i).align(4), ": ", i.toRoman</
{{out}}
Line 4,690:
=={{header|Objeck}}==
{{trans|C sharp}}
<
bundle Default {
class Roman {
Line 4,723:
}
}
</syntaxhighlight>
=={{header|OCaml}}==
Line 4,729:
With an explicit decimal digit representation list:
<
1 -> [x]
| 2 -> [x;x]
Line 4,751:
digit 'X' 'L' 'C' (x / 10) @ to_roman (x mod 10)
else
digit 'I' 'V' 'X' x</
{{out}}
Line 4,765:
=={{header|Oforth}}==
<
: roman(n)
| r |
StringBuffer new
Romans forEach: r [ while(r first n <=) [ r second << n r first - ->n ] ] ;</
=={{header|OpenEdge/Progress}}==
<
i_i AS INT
):
Line 4,809:
1666 encodeRoman( 1666 ) SKIP
VIEW-AS ALERT-BOX.
</syntaxhighlight>
{{out}}
<pre>---------------------------
Line 4,824:
=={{header|Oz}}==
{{trans|Haskell}}
<
fun {Digit X Y Z K}
unit([X] [X X] [X X X] [X Y] [Y] [Y X] [Y X X] [Y X X X] [X Z])
Line 4,840:
end
in
{ForAll {Map [1999 25 944] ToRoman} System.showInfo}</
=={{header|PARI/GP}}==
Old-style Roman numerals
<
while(n>999999,
n-=1000000;
Line 4,898:
);
print()
};</
This simple version of medieval Roman numerals does not handle large numbers.
<
while(n>999,
n-=1000;
Line 4,955:
);
print()
};</
=={{header|Pascal}}==
Line 4,962:
=={{header|Peloton}}==
Roman numbers are built in to Peloton as a particular form of national number. However, for the sake of the task the _RO opcode has been defined.
<
<@ ENU$$DLSTLITLIT>1990,2008,1,2,64,124,1666,10001|,|
<@ SAYELTLST>...</@> is <@ SAY_ROELTLSTLIT>...|RomanLowerUnicode</@> <@ SAY_ROELTLSTLIT>...|RomanUpperUnicode</@> <@ SAY_ROELTLSTLIT>...|RomanASCII</@>
</@></
Same code in padded-out, variable-length English dialect
<
<# ENUMERATION LAMBDASPECIFIEDDELMITER LIST LITERAL LITERAL>1990,2008,1,2,64,124,1666,10001|,|
<# SAY ELEMENT LIST>...</#> is <# SAY _RO ELEMENT LIST LITERAL>...|RomanLowerUnicode</#> <# SAY _RO ELEMENT LIST LITERAL>...|RomanUpperUnicode</#> <# SAY _RO ELEMENT LIST LITERAL>...|RomanASCII</#>
</#></
{{out}} Notice here the three different ways of representing the results.
Line 4,989:
==== Simple program ====
Simple, fast, produces same output as the Math::Roman module and the Raku example, less crazy than writing a Latin program, and doesn't require experimental modules like the Raku translation.
<
sub roman {
Line 5,002:
}
say roman($_) for 1..2012;</
==== Using a module ====
<
say roman($_) for 1..2012'</
==== Ported version of Raku ====
<
my %symbols = (
Line 5,031:
};
print roman($_) . "\n" for 1..2012;</
=={{header|Phix}}==
<!--<
<span style="color: #008080;">function</span> <span style="color: #000000;">toRoman</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">v</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">roman</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"M"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"CM"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"D"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"CD"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"C"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"XC"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"L"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"XL"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"X"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"IX"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"V"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"IV"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"I"</span><span style="color: #0000FF;">},</span>
Line 5,051:
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1990</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2008</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1666</span><span style="color: #0000FF;">},</span><span style="color: #000000;">toRoman</span><span style="color: #0000FF;">)</span>
<!--</
{{out}}
<pre>
Line 5,058:
=={{header|Phixmonti}}==
<
def romanEnc /# n -- s #/
Line 5,081:
enddef
1968 romanEnc print</
{{trans|Lua}}
<
var k
( ( 1000 "M" ) ( 900 "CM" ) ( 500 "D" ) ( 400 "CD" ) ( 100 "C" ) ( 90 "XC" )
Line 5,100:
enddef
1968 romanEnc</
Without vars
<
>ps
( ( 1000 "M" ) ( 900 "CM" ) ( 500 "D" ) ( 400 "CD" ) ( 100 "C" ) ( 90 "XC" )
Line 5,120:
enddef
1968 romanEnc</
=={{header|PHP}}==
{{works with|PHP|4+ tested in 5.2.12}}
<
/**
* int2roman
Line 5,185:
return $numeral . $leastSig;
}
</syntaxhighlight>
=={{header|Picat}}==
<
List = [455,999,1990,1999,2000,2001,2008,2009,2010,2011,2012,1666,3456,3888,4000],
foreach(Val in List)
Line 5,208:
end
end
end.</
{{out}}
Line 5,229:
===Longest numeral===
Which number encodes to the longest Roman numerals in the interval 1..4000:
<
All = [Len=I=roman_encode(I) : I in 1..4000,E=roman_encode(I), Len=E.len].sort_down,
println(All[1..2]),
nl.</
{{out}}
Line 5,238:
=={{header|PicoLisp}}==
<
(pack
(make
Line 5,247:
(link C) ) )
'(M CM D CD C XC L XL X IX V IV I)
(1000 900 500 400 100 90 50 40 10 9 5 4 1) ) ) ) )</
{{out}}
<pre>: (roman 1009)
Line 5,256:
=={{header|Pike}}==
<
int main(){
write(int2roman(2009) + "\n");
write(int2roman(1666) + "\n");
write(int2roman(1337) + "\n");
}</
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
/* From Wiki Fortran */
roman: procedure (n) returns(character (32) varying);
Line 5,284:
return (r);
end roman;
</syntaxhighlight>
Results:
<pre>
Line 5,295:
=={{header|PL/SQL}}==
<syntaxhighlight lang="pl/sql">
/*****************************************************************
Line 5,321:
END;
</syntaxhighlight>
=={{header|plainTeX}}==
TeX has its own way to convert a number into roman numeral, but it produces lowercase letters; the following macro (and usage example), produce uppercase roman numeral.
<
Anno Domini \upperroman{\year}
\bye</
=={{header|PowerBASIC}}==
Line 5,337:
{{works with|PB/CC|5}}
<
DIM arabic(0 TO 12) AS INTEGER
DIM roman(0 TO 12) AS STRING
Line 5,360:
? "1666 = " & toRoman(1666)
? "3888 = " & toRoman(3888)
END FUNCTION</
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
Filter ToRoman {
$output = ''
Line 5,401:
$output
}
</syntaxhighlight>
<syntaxhighlight lang="powershell">
19,4,0,2479,3001 | ToRoman
</syntaxhighlight>
{{Out}}
<pre>
Line 5,418:
{{libheader|clpfd}}
Library clpfd assures that the program works in both managements : Roman towards Arabic and Arabic towards Roman.
<
roman :-
Line 5,520:
my_print(A, R) :-
format('~w in roman is ~w~n', [A, R]).
</syntaxhighlight>
{{out}}
<pre> ?- roman.
Line 5,532:
=={{header|PureBasic}}==
<
DataSection
denominations:
Line 5,587:
Input()
CloseConsole()
EndIf</
=={{header|Python}}==
===Pythonic===
<
print(roman.toRoman(2022))</
===Imperative===
# Version for Python 2
<
adjust_roman = "CCXXmmccxxii";
arabic = (1000000, 500000, 100000, 50000, 10000, 5000, 1000, 500, 100, 50, 10, 5, 1);
Line 5,619:
2000,2008,2500,3000,4000,4999,5000,6666,10000,50000,100000,500000,1000000);
for val in test:
print '%d - %s'%(val, arabic_to_roman(val))</
An alternative which uses the divmod() function<
def ToRoman(num):
Line 5,635:
else:
namoR += r*romanDgts[rdix] + (romanDgts[rdix+1] if(v==1) else '')
return namoR[-1::-1]</
It is more Pythonic to use zip to iterate over two lists together:
<
rnums = "M CM D CD C XC L XL X IX V IV I".split()
Line 5,656:
for val in test:
print '%d - %s'%(val, to_roman(val))
</syntaxhighlight>
# Version for Python 3
<
#===========================
'''Convert an integer from the decimal notation to the Roman notation'''
Line 5,680:
for val in test:
print("%8d %s" %(val, arabic_to_roman(val)))</
===Declarative===
Less readable, but a 'one liner':
<
'6' : 'DC', '5' : 'D', '4' : 'CD', '3' : 'CCC', '2' : 'CC', '1' : 'C', '0' : '' }, { '9' : 'XC',
'8' : 'LXXX', '7' : 'LXX', '6' : 'LX', '5' : 'L', '4' : 'XL', '3' : 'XXX', '2' : 'XX', '1' : 'X',
Line 5,694:
# Option 2
def number2romannumeral(n):
return reduce(lambda x, y: x + y, map(lambda x, y: rnl[x][y], range(4), str(n).zfill(4))) if -1 < n < 5000 else None</
Line 5,700:
{{works with|Python|3}}
{{Trans|Haskell}}
<
from functools import reduce
Line 5,770:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>MDCLXVI
Line 5,780:
=={{header|QBasic}}==
<
DIM SHARED roman$(0 TO 12)
Line 5,804:
PRINT "2009 = "; toRoman$(2009)
PRINT "1666 = "; toRoman$(1666)
PRINT "3888 = "; toRoman$(3888)</
=={{header|Quackery}}==
Line 5,810:
Pasting epitomised.
<
swap 1000 /mod $ "M" rot of rot swap join swap
dup 900 < not if [ 900 - dip [ $ "CM" join ] ]
Line 5,828:
1990 dup echo say " = " ->roman echo$ cr
2008 dup echo say " = " ->roman echo$ cr
1666 dup echo say " = " ->roman echo$ cr</
{{Out}}
Line 5,838:
=={{header|R}}==
R has a built-in function, <code>[https://svn.r-project.org/R/trunk/src/library/utils/R/roman.R as.roman]</code>, for conversion to Roman numerals. The implementation details are found in <code>utils:::.numeric2roman</code> (see previous link), and <code>utils:::.roman2numeric</code>, for conversion back to Arabic decimals.
<
Since the object <code>as.roman</code> creates is just an integer vector with a class, you can do arithmetic with Roman numerals:
<
=={{header|Racket}}==
Straight recursion:
<
(define (encode/roman number)
(cond ((>= number 1000) (string-append "M" (encode/roman (- number 1000))))
Line 5,859:
((>= number 4) (string-append "IV" (encode/roman (- number 4))))
((>= number 1) (string-append "I" (encode/roman (- number 1))))
(else "")))</
Using for/fold and quotient/remainder to remove repetition:
<
(define (number->list n)
(for/fold ([result null])
Line 5,879:
1000 1009 1444 1666 1945 1997 1999 2000 2008 2010 2011 2500
3000 3999)])
(printf "~a ~a\n" n (encode/roman n)))</
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
1 => "I", 5 => "V", 10 => "X", 50 => "L", 100 => "C",
500 => "D", 1_000 => "M";
Line 5,905:
for 1 .. 2_010 -> $x {
say roman($x);
}</
=={{header|Red}}==
Straight iterative solution:
<syntaxhighlight lang="red">
table: [1000 M 900 CM 500 D 400 CD 100 C 90 XC 50 L 40 XL 10 X 5 V 4 IV 1 I]
Line 5,919:
foreach number [40 33 1888 2016][print [number ":" to-Roman number]]
</syntaxhighlight>
Straight recursive solution:
<syntaxhighlight lang="red">
table: [1000 M 900 CM 500 D 400 CD 100 C 90 XC 50 L 40 XL 10 X 5 V 4 IV 1 I]
Line 5,933:
foreach number [40 33 1888 2016][print [number ":" to-Roman number]]
</syntaxhighlight>
This solution builds, using metaprogramming, a `case` table, that relies on recursion to convert every digit.
<syntaxhighlight lang="red">
to-Roman: function [n [integer!]] reduce [
'case collect [
Line 5,946:
foreach number [40 33 1888 2016][print [number ":" to-Roman number]]
</syntaxhighlight>
=={{header|Retro}}==
This is a port of the [[Forth]] code; but returns a string rather than displaying the roman numerals. It only handles numbers between 1 and 3999.
<syntaxhighlight lang="retro">
: vector ( ...n"- )
here [ &, times ] dip : .data ` swap ` + ` @ ` do ` ; ;
Line 5,976:
dup 1 3999 within 0 =
[ "EX LIMITO!\n" ] [ "IVXLCDM" swap record here ] if ;
</syntaxhighlight>
=={{header|REXX}}==
===version 1===
<
arg number
Line 5,996:
end
end
return result</
===version 2===
This version of a REXX program allows almost any non-negative decimal integer.
Line 6,014:
The general REXX code is bulkier than most at it deals with ''any'' non-negative decimal number, and more
<br>boilerplate code is in the general REXX code to handle the above versions.
<
numeric digits 10000 /*decimal digs can be higher if wanted.*/
parse arg # /*obtain optional integers from the CL.*/
Line 6,066:
if pos(_, #)\==0 then #=changestr(_, #, copies('M', i))
end /*i*/
return #</
Some older REXXes don't have a '''changestr''' BIF, so one is included here ──► [[CHANGESTR.REX]]. <br><br>
'''output''' when using the default (internal) input):
Line 6,164:
=={{header|Ring}}==
<
arabic = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
roman = ["M", "CM", "D", "CD", "C" ,"XC", "L", "XL" ,"X", "IX", "V", "IV", "I"]
Line 6,181:
next
return result
</syntaxhighlight>
=={{header|Ruby}}==
Roman numeral generation was used as an example for demonstrating [http://www.xpsd.org/cgi-bin/wiki?TestDrivenDevelopmentTutorialRomanNumerals Test Driven Development] in Ruby. The solution came to be:
<
Subtractors = [ [1000, 100], [500, 100], [100, 10], [50, 10], [10, 1], [5, 1], [1, 0] ]
Line 6,198:
[1990, 2008, 1666].each do |i|
puts "%4d => %s" % [i, roman(i)]
end</
{{out}}
Line 6,209:
Another shorter version if we don't consider calculating the substractors:
<
Symbols = [ [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'] ]
Line 6,216:
Symbols.each { |arabic_rep, roman_rep| return roman_rep + arabic_to_roman(arabic - arabic_rep) if arabic >= arabic_rep }
end
</syntaxhighlight>
Yet another way to solve it in terms of reduce
<
Symbols = [ [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'] ]
Line 6,229:
end
end
</syntaxhighlight>
=={{header|Run BASIC}}==
<
input "Input value:";val$
print roman$(val$)
Line 6,251:
wend
next i
END FUNCTION</
=={{header|Rust}}==
<
symbol: &'static str,
value: u32
Line 6,292:
println!("{:2$} = {}", n, to_roman(n), 4);
}
}</
<pre>
2014 = MMXIV
Line 6,303:
=={{header|Scala}}==
{{works with|Scala|2.8}}
<
1 -> "I", 5 -> "V",
10 -> "X", 50 -> "L",
Line 6,315:
case Some(key) => romanDigits(key) + toRoman(n - key)
case None => ""
}</
{{Out}}
<pre>scala> List(1990, 2008, 1666) map toRoman
res55: List[String] = List(MCMXC, MMVIII, MDCLXVI)</pre>
===Using foldLeft===
<
val romanNumerals = List(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")
Line 6,333:
test(1990)
test(2008)
test(1666)</
===Different code-style===
<
case class RomanUnit(value: Int, token: String)
val romanNumerals = List(
Line 6,360:
}
}
}</
{{out}}
<pre>1990 => MCMXC
Line 6,369:
This uses format directives supported in Chez Scheme since v6.9b; YMMV.
<
(format "~@r" n))</
This is a general example using Chicken Scheme.
<
'(("M" . 1000)
("CM" . 900)
Line 6,407:
(printf "~a ~a\n" (car n) (to-roman (car n)))
(loop (cdr n))))
</syntaxhighlight>
=={{header|Seed7}}==
Line 6,415:
which writes a roman numeral to a string.
<
include "stdio.s7i";
include "wrinum.s7i";
Line 6,426:
writeln(str(ROMAN, number));
end for;
end func;</
Original source [http://seed7.sourceforge.net/algorith/puzzles.htm#roman_numerals].
Line 6,432:
=={{header|SenseTalk}}==
<
put [
(1, "I"),
Line 6,458:
end repeat
return numerals
end RomanNumeralsEncode</
<
1990,
2008,
Line 6,466:
]
put RomanNumeralsEncode(it)
end repeat</
{{out}}
Line 6,476:
=={{header|SETL}}==
<
for example in examples loop
Line 6,492:
end loop;
return roman;
end;</
{{out}}
<pre>MMVIII
Line 6,499:
=={{header|Shen}}==
<
(define encodeGlyphs
ACC 0 _ -> ACC
Line 6,509:
N -> (encodeGlyphs "" N ["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])
)
</syntaxhighlight>
{{out}}
<pre>
Line 6,524:
=={{header|Sidef}}==
{{trans|ActionScript}}
<
static lookup = [
:M:1000, :CM:900, :D:500,
Line 6,542:
say("1990 in roman is " + arabic2roman(1990));
say("2008 in roman is " + arabic2roman(2008));
say("1666 in roman is " + arabic2roman(1666));</
{{out}}
<pre>1990 in roman is MCMXC
Line 6,549:
=={{header|Simula}}==
<
TEXT PROCEDURE TOROMAN(N); INTEGER N;
Line 6,589:
END PROGRAM;
</syntaxhighlight>
{{out}}
<pre>
Line 6,601:
{{works with|Smalltalk/X}}
in ST/X, integers already know how to print themselves as roman number:
<syntaxhighlight lang
{{out}}
<pre>
MMXIII</pre>
the implementation is:
<
printRomanOn:aStream naive:naive
"print the receiver as roman number to the argument, aStream.
Line 6,660:
] doWhile:[ repeatFlag and:[ restValue >= rValue] ].
].
</syntaxhighlight>
=={{header|SNOBOL4}}==
Adapted from [http://burks.bton.ac.uk/burks/language/snobol/catspaw/tutorial/ch6.htm Catspaw SNOBOL Tutorial, Chapter 6]
<
* ROMAN(N) - Convert integer N to Roman numeral form.
*
Line 6,696:
OUTPUT = " 944 = " ROMAN(944)
END</
{{out}}
<pre>
Line 6,706:
Here's a non-recursive version, and a Roman-to-Arabic converter to boot.
<
define('roman(n)s,ch,val,str') :(roman_end)
roman roman = ge(n,4000) n :s(return)
Line 6,734:
astr = astr r '=' arabic(r) ' ' :(tloop)
out output = rstr; output = astr
end</
{{out}}
Line 6,741:
=={{header|SPL}}==
<
r = ""
n = [["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"],[1000,900,500,400,100,90,50,40,10,9,5,4,1]]
Line 6,756:
> i, 1..#.size(t,1)
#.output(t[i]," = ",a2r(t[i]))
<</
{{out}}
<pre>
Line 6,765:
=={{header|SQL}}==
<syntaxhighlight lang="sql">
--
-- This only works under Oracle and has the limitation of 1 to 3999
Line 6,775:
--------------- ---------------
MDCLXVI mdclxvi
</syntaxhighlight>
=={{header|Swift}}==
<
var result = ""
Line 6,803:
}
return result
}</
Sample call:
{{works with|Swift|1.x}}
<
{{works with|Swift|2.0}}
<
{{output}}
<pre>MDCLXVI </pre>
=={{header|Tailspin}}==
<
def digits: [(M:1000"1"), (CM:900"1"), (D:500"1"), (CD:400"1"), (C:100"1"), (XC:90"1"), (L:50"1"), (XL:40"1"), (X:10"1"), (IX:9"1"), (V:5"1"), (IV:4"1"), (I:1"1")];
templates encodeRoman
Line 6,833:
' -> !OUT::write
1666 -> encodeRoman -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
Line 6,842:
=={{header|Tcl}}==
<
set map {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}
foreach {value roman} $map {
Line 6,851:
}
return $res
}</
=={{header|TI-83 BASIC}}==
<
:"="→Str1
:Lbl ST
Line 6,938:
:Pause
:Goto ST
</syntaxhighlight>
=={{header|True BASIC}}==
<
DIM arabic(12), roman$(12)
Line 6,966:
PRINT "1666 = "; toRoman$(1666)
PRINT "3888 = "; toRoman$(3888)
END</
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
LOOP arab_number="1990'2008'1666"
Line 6,976:
PRINT "Arabic number ",arab_number, " equals ", roman_number
ENDLOOP
</syntaxhighlight>
{{out}}
<pre>
Line 6,987:
{{trans|DWScript}}
Weights and symbols in tuples.
<
// Roman numerals/Encode
Line 7,011:
console.log(toRoman(2022)); // MMXXII
console.log(toRoman(3888)); // MMMDCCCLXXXVIII
</syntaxhighlight>
{{out}}
<pre>
Line 7,021:
=={{header|uBasic/4tH}}==
{{trans|BBC Basic}}
<syntaxhighlight lang="text">Push 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000
' Initialize array
For i = 12 To 0 Step -1
Line 7,059:
110 Print "D"; : Return
120 Print "CM"; : Return
130 Print "M"; : Return</
=={{header|UNIX Shell}}==
{{trans|Tcl}}
{{works with|bash}}
<
local values=( 1000 900 500 400 100 90 50 40 10 9 5 4 1 )
local roman=(
Line 7,085:
for test in 1999 24 944 1666 2008; do
printf "%d = %s\n" $test $(roman $test)
done</
{{out}}
<pre>
Line 7,103:
CCCC are replaced by CD. The substitution operator (%=) is helpful
here.
<
roman =
Line 7,109:
-+
'IIII'%='IV'+ 'VIIII'%='IX'+ 'XXXX'%='XL'+ 'LXXXX'%='XC'+ 'CCCC'%='CD'+ 'DCCCC'%='CM',
~&plrDlSPSL/'MDCLXVI'+ iota*+ +^|(^|C/~&,\/division)@rlX=>~&iNC <1000,500,100,50,10,5>+-</
This test program applies the function to each member of a list of numbers.
<
test = roman* <1990,2008,1,2,64,124,1666,10001></
{{out}}
<pre>MCMXC
Line 7,126:
=={{header|Vala}}==
{{trans|D}}
<
requires (n > 0 && n < 5000)
{
Line 7,151:
print("%s\n", to_roman(3456));
print("%s\n", to_roman(2488));
}</
{{out}}
Line 7,161:
=={{header|VBA}}==
<
roman = WorksheetFunction.roman(n)
End Function
Line 7,169:
Debug.Print roman(CInt(x)); " ";
Next x
End Sub</
<pre>X MMXVI DCCC MMDCCLXIX MDCLXVI CDLXXVI MCDLIII </pre>
=={{header|Vedit macro language}}==
<
//
do {
Line 7,204:
}
Buf_Quit(OK)
Return</
{{out}}
Line 7,216:
{{trans|BASIC}}
<
Dim arabic As Variant
Dim roman As Variant
Line 7,237:
Sub Main()
MsgBox toRoman(Val(InputBox("Number, please")))
End Sub</
=={{header|Wren}}==
{{trans|Kotlin}}
<
[1000, "M"],
[900, "CM"],
Line 7,272:
System.print(encode.call(1666))
System.print(encode.call(2008))
System.print(encode.call(2020))</
{{out}}
Line 7,285:
{{trans|DWScript}}
{{works with|Windows XBasic}}
<
PROGRAM "romanenc"
VERSION "0.0000"
Line 7,344:
END FUNCTION
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
Line 7,353:
=={{header|XLISP}}==
<
(define roman-numerals '((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")))
(defun romanize (arabic-numeral numerals roman-numeral)
Line 7,364:
; test the function:
(display (mapcar roman '(10 2016 800 2769 1666 476 1453)))</
{{out}}
<pre>(x mmxvi dccc mmdcclxix mdclxvi cdlxxvi mcdliii)</pre>
=={{header|XPL0}}==
<
int N, A, B, C, I;
[case N of
Line 7,393:
for I:= 0 to 7 do
[IntOut(0, Tbl(I)); Text(0, ". "); Roman(Tbl(I)); CrLf(0)];
]</
{{out}}
Line 7,408:
=={{header|XSLT}}==
<
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/data/number">
Line 7,459:
</xsl:template>
</xsl:stylesheet>
</syntaxhighlight>
=={{header|Yabasic}}==
<
decml$ = "1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1"
Line 7,492:
// 2009 = MMIX
// 1666 = MDCLXVI
// 3888 = MMMDCCCLXXXVIII</
=={{header|zkl}}==
<
L("M", 1000), L("CM", 900), L("D", 500), L("CD", 400), L("C", 100),
L("XC", 90), L("L", 50), L("XL", 40), L("X", 10), L("IX", 9),
Line 7,503:
foreach R,N in (romans){ text += R*(i/N); i = i%N; }
return(text);
}</
<pre>
toRoman(1990) //-->"MCMXC"
Line 7,511:
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
program: decimal_roman
input: 12
output: 'XII'
</syntaxhighlight>
=={{header|Zoea Visual}}==
Line 7,522:
=={{header|Zsh}}==
Based on the python solution.
<
local -a conv
local number=$1 div rom num out
Line 7,533:
done
echo $out
}</
|