Skip to content

Instantly share code, notes, and snippets.

@smartwatermelon
Last active September 29, 2022 21:08
Show Gist options
  • Save smartwatermelon/f0c088a312e89b86e4ef62c650994a6d to your computer and use it in GitHub Desktop.
Save smartwatermelon/f0c088a312e89b86e4ef62c650994a6d to your computer and use it in GitHub Desktop.
@cassidoo's interview question from September 25, 2022
#!/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"
@smartwatermelon
Copy link
Author

MONTASIO:scripts andrewrich$ for N in {1..30}; do ./ordinalize.sh $N; done
1's ordinal is 1st
2's ordinal is 2nd
3's ordinal is 3rd
4's ordinal is 4th
5's ordinal is 5th
6's ordinal is 6th
7's ordinal is 7th
8's ordinal is 8th
9's ordinal is 9th
10's ordinal is 10th
11's ordinal is 11th
12's ordinal is 12th
13's ordinal is 13th
14's ordinal is 14th
15's ordinal is 15th
16's ordinal is 16th
17's ordinal is 17th
18's ordinal is 18th
19's ordinal is 19th
20's ordinal is 20th
21's ordinal is 21st
22's ordinal is 22nd
23's ordinal is 23rd
24's ordinal is 24th
25's ordinal is 25th
26's ordinal is 26th
27's ordinal is 27th
28's ordinal is 28th
29's ordinal is 29th
30's ordinal is 30th
MONTASIO:scripts andrewrich$ ./ordinalize.sh abc
error: Not a number

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