Some years ago I wrote an tool 'aroma' (and I think I also posted
a version here) for arabic <-> roman (bidirectional) conversion.
Here is the version I still have in my local bin directory...
Have fun!
Janis
# aroma - yet another arabic number / roman number converter
#
# Historically, a couple variants of roman numbers have been
# around, a couple alphabets were in use in different regions
# and times and various rules to build and interpret roman
# numbers were existing. In this code we restrict to the basic
# alphabet I, V, X, L, C, D, M and allow simple subtractive
# abbreviations IV, IX, XL, XC, CD, CM; this is often called
# the normal form of the roman numbers. (Deviations from that
# form, e.g. numbers like 'IM' or 'IIX', are not supported.)
#
# Janis Papanagnou, 2010
awk -v n="${1?Please provide a number (arabic or roman) as argument!}" '
BEGIN {
split ("1000 900 500 400 100 90 50 40 10 9 5 4 1", ar)
split ("M CM D CD C XC L XL X IX V IV I", ro)
if (n ~ /^[[:digit:]]+$/) {
print ar2ro(n) # output in unique normal form
} else if (n ~ /^[MDCLXVI]*$/) {
x = ro2ar(n) # a consistency test follows
print (ar2ro(x) == n) ? x : "NaN"
} else {
print "NaN"
}
}
function ro2ar (r, a, i)
{
a = 0
for (i=1; r && ro[i]; i++)
{
l = length (ro[i])
while (substr (r,1,l) == ro[i]) {
a += ar[i]
r = substr (r,l+1)
}
}
return (r == "") ? a : "NaN"
}
function ar2ro (a, r, i)
{
for (i=1; ar[i]; i++) {
while (a >= ar[i]) {
a -= ar[i]
r = r ro[i]
}
}
return r
}
'
# vim: ts=4 sw=4 syntax=awk
On 28.10.2023 02:22, Mike Sanders wrote:
# tags: roman, numbers, awk, code
#
# Arabic to Roman Number Conversion
# Michael Sanders 2023
# https://busybox.neocities.org/notes/arabic-to-roman.txt
#
# example usage: echo 6 | awk -f arabic-to-roman.txt
#
# note: using standard Roman numerals, the largest number
# that can be represented is 3,999, written as MMMCMXCIX
function toRoman(n) {
if (n !~ /^[0-9]+$/ || n < 1 || n > 3999) return "invalid input"
split("I IV V IX X XL L XC C CD D CM M", roman)
split("1 4 5 9 10 40 50 90 100 400 500 900 1000", arabic)
# loop through array in reverse order building romanNum
for (x = 13; x >= 1; x--) {
while (n >= arabic[x]) {
romanNum = romanNum roman[x]
n -= arabic[x]
}
}
return romanNum
}
{ print toRoman($1) }
# eof
--- SoupGate-Win32 v1.05
* Origin: fsxNet Usenet Gateway (21:1/5)