View previous topic :: View next topic |
Author |
Message |
Brent Site Admin
Joined: 01 Jul 2005 Posts: 790
|
Posted: Feb 4th, 2014, 5:01am Post subject: Roman numeral encoder in Windows batch |
|
|
Every now and then I like to challenge myself by writing a program in Windows batch just to see if it can be done. This is a task from Rosetta Code to convert a number to Roman numeral.
Code: | @Echo Off
SetLocal EnableDelayedExpansion
For %%n In (1666 1888 1999 2000) Do (
Call :toRoman %%n
Echo %%n = !roman!
)
GoTo :EOF
:toRoman value
:: Converts an integer value to a Roman numeral. Result is in %roman%.
Set value=%1
Set "Roman="
If Not Defined arabic.0 (
Call :SetArray arabic 0=1000 1=900 2=500 3=400 4=100 5=90 6=50 7=40 8=10 9=9 10=5 11=4 12=1
Call :SetArray roman 0=M 1=CM 2=D 3=CD 4=C 5=XC 6=L 7=XL 8=X 9=IX 10=V 11=IV 12=I
)
For /L %%i In (0,1,12) Do Call :toRoman_Loop %%i
GoTo :EOF
:toRoman_Loop 1
:: Called by :toRoman to do much of the work. No other code should call this.
If !value! LSS !arabic.%1! GoTo :EOF
Set "Roman=!Roman!!roman.%1!"
Set /A value-=!arabic.%1!
GoTo toRoman_Loop
:SetArray name index1=value1 index2=value2 etc
:: Creates a pseudo-array of variables of the form "name.index"
If "%2" EQU "" GoTo :EOF
Set "%1.%2=%3"
Shift /2
Shift /2
GoTo SetArray |
_________________ Brent
Last edited by Brent on Feb 5th, 2014, 5:28pm; edited 1 time in total |
|
Back to top |
|
 |
STPendl Full Member
Joined: 20 Aug 2007 Posts: 161 Location: Austria
|
Posted: Feb 4th, 2014, 7:21pm Post subject: Re: Roman numeral encoder in Windows batch |
|
|
This is a nice showcase of working around the shortcomings of Windows command scripts
I really like this approach  _________________ Stefan
Any code I post can be freely used, just give credit. |
|
Back to top |
|
 |
Brent Site Admin
Joined: 01 Jul 2005 Posts: 790
|
Posted: Feb 5th, 2014, 5:36pm Post subject: Re: Roman numeral encoder in Windows batch |
|
|
Thanks, Stefan.
BTW, I edited the code to eliminate any chance of accidental spaces that might be introduced by the forum software. _________________ Brent |
|
Back to top |
|
 |
|