Skip to content

Instantly share code, notes, and snippets.

@pysysops
Created November 27, 2018 19:02
Show Gist options
  • Save pysysops/0300b3380a6cbdca98bdba592645d32d to your computer and use it in GitHub Desktop.
Save pysysops/0300b3380a6cbdca98bdba592645d32d to your computer and use it in GitHub Desktop.
Convert numbers to Roman numerals
#!/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}
@johnpemberton
Copy link

Thing of beauty

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment