| 1 | #!/bin/bash |
| 2 | |
| 3 | # Arabic number to Roman numeral conversion |
| 4 | # Range: 0 - 200 |
| 5 | # It's crude, but it works. |
| 6 | |
| 7 | # Extending the range and otherwise improving the script is left as an exercise. |
| 8 | |
| 9 | # Usage: roman number-to-convert |
| 10 | |
| 11 | LIMIT=200 |
| 12 | E_ARG_ERR=65 |
| 13 | E_OUT_OF_RANGE=66 |
| 14 | |
| 15 | if [ -z "$1" ] |
| 16 | then |
| 17 | echo "Usage: `basename $0` number-to-convert" |
| 18 | exit $E_ARG_ERR |
| 19 | fi |
| 20 | |
| 21 | num=$1 |
| 22 | if [ "$num" -gt $LIMIT ] |
| 23 | then |
| 24 | echo "Out of range!" |
| 25 | exit $E_OUT_OF_RANGE |
| 26 | fi |
| 27 | |
| 28 | to_roman () # Must declare function before first call to it. |
| 29 | { |
| 30 | number=$1 |
| 31 | factor=$2 |
| 32 | rchar=$3 |
| 33 | let "remainder = number - factor" |
| 34 | while [ "$remainder" -ge 0 ] |
| 35 | do |
| 36 | echo -n $rchar |
| 37 | let "number -= factor" |
| 38 | let "remainder = number - factor" |
| 39 | done |
| 40 | |
| 41 | return $number |
| 42 | # Exercises: |
| 43 | # --------- |
| 44 | # 1) Explain how this function works. |
| 45 | # Hint: division by successive subtraction. |
| 46 | # 2) Extend to range of the function. |
| 47 | # Hint: use "echo" and command-substitution capture. |
| 48 | } |
| 49 | |
| 50 | |
| 51 | to_roman $num 100 C |
| 52 | num=$? |
| 53 | to_roman $num 90 LXXXX |
| 54 | num=$? |
| 55 | to_roman $num 50 L |
| 56 | num=$? |
| 57 | to_roman $num 40 XL |
| 58 | num=$? |
| 59 | to_roman $num 10 X |
| 60 | num=$? |
| 61 | to_roman $num 9 IX |
| 62 | num=$? |
| 63 | to_roman $num 5 V |
| 64 | num=$? |
| 65 | to_roman $num 4 IV |
| 66 | num=$? |
| 67 | to_roman $num 1 I |
| 68 | # Successive calls to conversion function! |
| 69 | # Is this really necessary??? Can it be simplified? |
| 70 | |
| 71 | echo |
| 72 | |
| 73 | exit |