Converting decimal to roman using sed
am 02.10.2007 03:50:49 von Tiago Peczenyj
Hi
This is a sed script to convert some decimal number between 1 and 4999
in roman:
---
s/1...$/M&/;s/2...$/MM&/;s/3...$/MMM&/;s/4...$/MMMM&/
s/6..$/DC&/;s/7..$/DCC&/;s/8..$/DCCC&/;s/9..$/CM&/
s/1..$/C&/;s/2..$/CC&/;s/3..$/CCC&/;s/4..$/CD&/;s/5..$/D&/
s/6.$/KX&/;s/7.$/LXX&/;s/8.$/LXXX&/;s/9.$/XC&/
s/1.$/X&/;s/2.$/XX&/;s/3.$/XXX&/;s/4.$/XL&/;s/5.$/L&/
s/1$/I/;s/2$/II/;s/3$/III/;s/4$/IV/;s/5$/V/
s/6$/VI/;s/7$/VII/;s/8$/VIII/;s/9$/IX/
s/[0-9]//g
---
sed -f script.sed <
1
51
404
1056
4999
EOF
I
LI
CDIV
MLVI
MMMMCMXCIX
Ok... its a dumb example but... is funny too :)
Re: Converting decimal to roman using sed
am 02.10.2007 10:19:17 von Janis Papanagnou
On 2 Okt., 03:50, Tiago Peczenyj wrote:
> Hi
>
> This is a sed script to convert some decimal number between 1 and 4999
> in roman:
>
> ---
> s/1...$/M&/;s/2...$/MM&/;s/3...$/MMM&/;s/4...$/MMMM&/
> s/6..$/DC&/;s/7..$/DCC&/;s/8..$/DCCC&/;s/9..$/CM&/
> s/1..$/C&/;s/2..$/CC&/;s/3..$/CCC&/;s/4..$/CD&/;s/5..$/D&/
> s/6.$/KX&/;s/7.$/LXX&/;s/8.$/LXXX&/;s/9.$/XC&/
Typo! - there's no roman digit 'K'.
> s/1.$/X&/;s/2.$/XX&/;s/3.$/XXX&/;s/4.$/XL&/;s/5.$/L&/
> s/1$/I/;s/2$/II/;s/3$/III/;s/4$/IV/;s/5$/V/
> s/6$/VI/;s/7$/VII/;s/8$/VIII/;s/9$/IX/
> s/[0-9]//g
> ---
>
> sed -f script.sed <
> 1
> 51
> 404
> 1056
> 4999
> EOF
>
> I
> LI
> CDIV
> MLVI
> MMMMCMXCIX
>
> Ok... its a dumb example but... is funny too :)
Nice.
Reminds me one of my programs ~30 years ago which has been something
like (now rewritten in awk code)...
BEGIN { n=split("1 4 5 9 10 40 50 90 100 400 500 900 1000", a)
split("I IV V IX X XL L XC C CD D CM M", r) }
{ z=$1; s="";
for (i=n; z; i--) {
while (z>=a[i]) { z-=a[i]; s=s r[i] }
}
print s
}
Janis
Re: Converting decimal to roman using sed
am 04.10.2007 01:04:18 von brian_hiles
Tiago Peczenyj wrote:
> This is a sed script to convert some decimal number between 1 and 4999
Ah. This reminds me of an ex(1) macro that I saw in an O'Reilly
book 10 years ago (perhaps "Learning the vi Editor"?) -- which
did recognize "K" ;) Alas, nothing is ever completely new....
Also, there is Carlos Duarte's script at:
http://cgd.sdf-eu.org/a/scripts/convert/fr_roman.sed
Although I like CD's script for utilizing RE forms that can
be auto-optimized into string manipulations, CD then ruins his
implementation by then requiring a final stage that utilizes
a clumsy hack to perform pseudo-addition, whereas yours
doesn't. So yours may be the better implementation, but I'd like
to have seen CD's version rewritten with Greg Ubben's hack for
doing efficient integral arithmetic in sed(1). BTW, direct
your peepers at the hack of all hacks, GU's audacious dc(1)
emulator:
http://sed.sf.net/local/scripts/dc.sed # currently inaccessible!
I guess this is the advantage of having written and used
a sed debugger that nobody has ever indicated been used. :(
=Brian (":P")