-
-
Save ewe2/a96bfa36614ba03e2a193f7449471577 to your computer and use it in GitHub Desktop.
Convert roman numerals to a number in BASH
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 | |
roman_numerals=$(echo $1 | tr a-z A-Z) | |
# Test that it is valid | |
[[ "${roman_numerals//[IVXLCDM]/}" == "" ]] || \ | |
{ echo Roman numerals ${roman_numerals} contains invalid characters ; \ | |
exit 1 ;} | |
# We want to replace all tokens to eventually have | |
# all I's, remove new lines and count the characters. | |
number=$( | |
echo ${roman_numerals} | | |
sed 's/CM/DCD/g' | | |
sed 's/M/DD/g' | | |
sed 's/CD/CCCC/g' | | |
sed 's/D/CCCCC/g' | | |
sed 's/XC/LXL/g' | | |
sed 's/C/LL/g' | | |
sed 's/XL/XXXX/g' | | |
sed 's/L/XXXXX/g' | | |
sed 's/IX/VIV/g' | | |
sed 's/X/VV/g' | | |
sed 's/IV/IIII/g' | | |
sed 's/V/IIIII/g' | | |
tr -d '\n' | | |
wc -m | |
) | |
echo ${roman_numerals} is ${number} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment