-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathroman.sh
More file actions
75 lines (67 loc) · 1.47 KB
/
roman.sh
File metadata and controls
75 lines (67 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/bin/bash
## https://www.fiverr.com/papashok
ARG="$1"
# print usage if no agument passed
if [[ -z "$ARG" ]];then
echo "Usage: bash $0 [ NUMBER ] or [ ROMAN ]"
echo "Example: bash $0 2018"
echo "Example: bash $0 MCMXCVIII"
exit 1
fi
to_roman() {
local VALUES=( 1000 900 500 400 100 90 50 40 10 5 4 1 )
# 1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC)
local R_VALUES=(
[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
)
local INUM=""
local NUM=$1
# loop from Array VALUES 1000 to 1
for VAL in ${VALUES[@]}; do
while (( NUM >= VAL )); do
INUM+=${R_VALUES[VAL]}
((NUM -= VAL))
done
done
echo $INUM
}
to_decimal() {
local ROMAN=$1
local INUM=0
local PREV=0
for ((i=${#ROMAN}-1;i>=0;i--));do
case "${ROMAN:$i:1}" in
M) VAL=1000 ;;
D) VAL=500 ;;
C) VAL=100 ;;
L) VAL=50 ;;
X) VAL=10 ;;
V) VAL=5 ;;
I) VAL=1 ;;
esac
if [[ $VAL -lt $PREV ]]
then
let INUM-=VAL
else
let INUM+=VAL
fi
PREV=$VAL
done
echo "$INUM"
}
# Check Argument decimal number
if [[ "$ARG" =~ ^[0-9]+$ ]];then
NUM=$ARG
to_roman "$NUM"
else
ROMAN=$ARG
# check only contains valid roman characters
if [[ "${ROMAN//[IVXLCDM]/}" != "" ]];then
echo "Roman numerals $ROMAN contains invalid characters"
exit 2
fi
to_decimal "$ROMAN"
fi