Created
November 27, 2018 19:02
-
-
Save pysysops/0300b3380a6cbdca98bdba592645d32d to your computer and use it in GitHub Desktop.
Convert numbers to Roman numerals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -eu -o pipefail | |
number=$1 | |
# Test that it is valid | |
[[ "${number//[0-9]/}" == "" ]] || \ | |
{ echo Number ${number} contains invalid characters ; \ | |
exit 1 ;} | |
# First we convert the number to a Roman Numeral unary representation | |
# then we replace appropriate chunks of tokens and end up with a Roman Numeral | |
# representation. | |
roman_numerals=$( | |
printf "%.sI" $(seq 1 ${number}) | | |
sed 's/IIIII/V/g' | | |
sed 's/IIII/IV/g' | | |
sed 's/VV/X/g' | | |
sed 's/VIV/IX/g' | | |
sed 's/XXXXX/L/g' | | |
sed 's/XXXX/XL/g' | | |
sed 's/LL/C/g' | | |
sed 's/LXL/XC/g' | | |
sed 's/CCCCC/D/g' | | |
sed 's/CCCC/CD/g' | | |
sed 's/DD/M/g' | | |
sed 's/DCD/CM/g' | |
) | |
echo ${number} is ${roman_numerals} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thing of beauty