- 论坛徽章:
- 145
|
本帖最后由 jason680 于 2015-06-15 12:00 编辑
回复 1# yestreenstars
What You Think Is What You Code(WYTIWYC)
I 1 (unus)
V 5 (quinque)
X 10 (decem)
L 50 (quinquaginta)
C 100 (centum)
D 500 (quingenti)
M 1,000 (mille)
0. prepare
array R for Roman number(I,V,X...)
array V for Value number(1,5,10,...)
1. check number ( 1 <= number <= 3999 )
if(S<1||3999<S){print "out of range 1~3999: "S;next}
2. check number with 10 times only (1000, 100, 10, and 1)
for(n=t;n>0;n-=2)
Note: t =7, and V[7] = 1000, V[5]=100, ...
3. for special number 4 and 9
4xx = 100 and 500 = CD (Note: R[5] and R[5+1], n=5)
9xx = 100 and 1000 = CM (Note: R[5] and R[5+2], n=5)
if(m%5==4){s=s R[n]R[n+(m>4?2:1)];
4. more than number 5
6x = 50 and 1x = LX (Note: R[3+1] and R[3])
7x = 50 and 2x = LXX
if(m>=5){s=s R[n+1];m-=5}
--------------------------------------------------------------------------
$ cat FILE
6
76
499
3888
9
4000
0
-1
$ awk '
BEGIN{
# 0. prepare
t=split("IVXLCDM",R,"");
for(n=1;n<=t;n++){
m=int(n/2);
N=10**m*(n%2?1:.5);
V[n]=N
}
}
{
S=N=$0;
# 1. check number ( 1 <= number <= 3999 )
if(S<1||3999<S){
print "out of range 1~3999: "S;
next
}
s="";
# 2. check number with 10 times only (1000, 100, 10, and 1)
for(n=t;n>0;n-=2){
if(N>=V[n]){
m=int(N/V[n]);
N%=V[n];
# 3. for special number 4 and 9
if(m%5==4){
s=s R[n]R[n+(m>4?2:1)];
continue
}
#4. more than number 5
if(m>=5){
s=s R[n+1];
m-=5
}
# for normal number
for(c=1;c<=m;c++)
s=s R[n]
}
}
print S,s
}' FILE
6 VI
76 LXXVI
499 CDXCIX
3888 MMMDCCCLXXXVIII
9 IX
out of range 1~3999: 4000
out of range 1~3999: 0
out of range 1~3999: -1
|
|