Last active
September 29, 2022 21:08
-
-
Save smartwatermelon/f0c088a312e89b86e4ef62c650994a6d to your computer and use it in GitHub Desktop.
@cassidoo's interview question from September 25, 2022
This file contains hidden or 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
#!/usr/bin/env bash | |
set -eu -o pipefail | |
# initialize vars | |
ordinal='' | |
# check input | |
ARGC="$#" | |
if [[ "$ARGC" -ne 1 ]]; then | |
echo "Please enter an integer number, e.g. 123" | |
exit 1 | |
fi | |
NUM="$1" | |
re='^[0-9]+$' | |
if ! [[ $NUM =~ $re ]] ; then | |
echo "error: Not a number" >&2; exit 1 | |
fi | |
# get ABS(NUM) | |
NUM=${NUM#-} | |
# get NUM mod 100 | |
## expr returns 1 if NUM ends in zero, but mod_num is correct, so we trap the error | |
mod_num=$( expr $NUM % 100 ) || : | |
# is NUM in the tweens set? | |
case $mod_num in | |
( '11' | '12'| '13' ) ordinal='th';; | |
('*') : ;; | |
esac | |
# get NUM mod 10 | |
## expr returns 1 if NUM ends in zero, but mod_num is correct, so we trap the error | |
mod_num=$( expr $NUM % 10 ) || : | |
# select appropriate suffix | |
if [ ! "$ordinal" ]; then | |
case $mod_num in | |
( '0' | '4' | '5' | '6' | '7' | '8' |'9' ) ordinal='th';; | |
('1') ordinal='st';; | |
('2') ordinal='nd';; | |
('3') ordinal='rd';; | |
('*') ordinal='error $NUM could not be ordinalized';; | |
esac | |
fi | |
if [[ $ordinal == *"error"* ]]; then | |
echo $ordinal | |
exit 1 | |
fi | |
echo "$NUM's ordinal is $NUM$ordinal" |
Author
smartwatermelon
commented
Sep 29, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment