Skip to content

Instantly share code, notes, and snippets.

@smartwatermelon
Created September 19, 2022 23:02
Show Gist options
  • Save smartwatermelon/827f5ae67e1f742cac08b5b723aeef57 to your computer and use it in GitHub Desktop.
Save smartwatermelon/827f5ae67e1f742cac08b5b723aeef57 to your computer and use it in GitHub Desktop.
@cassidoo's interview question from September 18, 2022
#!/usr/bin/env bash
set -eu -o pipefail
# initialize vars
runningTotal="0"
# normalized grade names to point values
A="4" AMINUS="3.7"
BPLUS="3.3" B="3" BMINUS="2.7"
CPLUS="2.3" C="2" CMINUS="1.7"
DPLUS="1.3" D="1" DMINUS="0.7"
F="0"
# normalize param to grade name
normalizeGradeParam () {
out="$( tr [':lower:'] [':upper:'] <<< "${1}" )"
case $out in
('A-') out="AMINUS";;
('B+') out="BPLUS";;
('B-') out="BMINUS";;
('C+') out="CPLUS";;
('C-') out="CMINUS";;
('D+') out="DPLUS";;
('D-') out="DMINUS";;
(A|B|C|D|F) : ;;
(*) out="invalid grade: ${out}";;
esac
echo "${out}"
}
ARGC="$#"
if [[ "$ARGC" -lt 1 ]]; then
echo "Please enter at least one grade from the set"
echo "A A- B+ B B- C+ C C- D+ D D- F"
exit 1
fi
for ARG in "$@"; do
grade=$( normalizeGradeParam $ARG )
if [[ $grade == *"invalid"* ]]; then
echo $grade
exit 1
fi
runningTotal=$( echo "scale=2;$runningTotal+${!grade}" | bc )
done
echo "GPA is $runningTotal / $ARGC = $(echo "scale=2;$runningTotal/$ARGC" | bc )"
@smartwatermelon
Copy link
Author

MONTASIO:scripts andrewrich$ ./calculateGPA.sh A a- B+ b B- c+ C c- D+ d D- f
GPA is 25.7 / 12 = 2.14
MONTASIO:scripts andrewrich$ ./calculateGPA.sh A a- B+ b B- c+ C c- D+ d D- f-
invalid grade: F-

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