Last active
September 23, 2023 11:32
-
-
Save nickbailey/bd01fdcd635f3f4a7726af16c02a040d to your computer and use it in GitHub Desktop.
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
# Convert a number from Roman notation to Arabic. | |
# Nick Bailey, nickbailey at github.com. 25th July 2023. | |
# From https://gist.github.com/pysysops/7596f1c0a5c6d14151bbd987a2fb95e5 | |
# Syntax check from the python roman package: https://pypi.org/project/roman/ | |
# | |
function roman () { | |
roman_numerals=$(echo $1 | tr a-z A-Z) | |
# Test that it is valid | |
[[ "${roman_numerals//[IVXLCDM]/}" == "" ]] || { | |
echo "Roman numerals $1 contains invalid characters" | |
return 1 | |
} | |
[[ $roman_numerals =~ ^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$ ]] || { | |
echo "$roman_numerals isn't a standard number" | |
return 2 | |
} | |
# We want to replace all tokens to eventually have | |
# all I's, remove new lines and count the characters. | |
number=$( | |
echo ${roman_numerals} | | |
sed -e 's/CM/DCD/g' -e 's/M/DD/g' -e 's/CD/CCCC/g' \ | |
-e 's/D/CCCCC/g' -e 's/XC/LXL/g' -e 's/C/LL/g' \ | |
-e 's/XL/XXXX/g' -e 's/L/XXXXX/g' -e 's/IX/VIV/g' \ | |
-e 's/X/VV/g' -e 's/IV/IIII/g' -e 's/V/IIIII/g' | | |
tr -d '\n' | | |
wc -m | |
) | |
echo ${number} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment