Last active
August 29, 2023 23:33
-
-
Save smartwatermelon/ec5bb95cd052f6fa34884f1b38238fb8 to your computer and use it in GitHub Desktop.
@cassidoo's interview question from August 28, 2023
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 | |
# Define function to convert a number to English words | |
# this function is lifted from my countSelfChars solution from April 2, 2023: | |
# https://gist.github.com/smartwatermelon/ab9b5886128e9120b1ad3deebb2f320f | |
function num_to_words { | |
local ones=( '' one two three four five six seven eight nine ) | |
local tens=( '' '' twenty thirty forty fifty sixty seventy eighty ninety ) | |
local specials=( ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen ) | |
local num=$1 | |
# Handle numbers greater than or equal to 1000 | |
if [[ $num -ge 1000 ]]; then | |
local thousands=$(( $num / 1000 )) | |
num=$(( $num % 1000 )) | |
echo -n "$(num_to_words $thousands) thousand " | |
fi | |
# Handle numbers between 100 and 999 | |
if [[ $num -ge 100 ]]; then | |
local hundreds=$(( $num / 100 )) | |
num=$(( $num % 100 )) | |
echo -n "${ones[$hundreds]} hundred " | |
if [[ $num -gt 0 ]]; then | |
echo -n "and " | |
fi | |
fi | |
# Handle numbers between 20 and 99 | |
if [[ $num -ge 20 ]]; then | |
local tens_place=$(( $num / 10 )) | |
num=$(( $num % 10 )) | |
echo -n "${tens[$tens_place]} " | |
fi | |
# Handle numbers between 10 and 19 | |
if [[ $num -ge 10 && $num -lt 20 ]]; then | |
local specials_place=$(( $num % 10 )) | |
echo -n "${specials[$specials_place]} " | |
num=0 | |
fi | |
# Handle numbers between 0 and 9 | |
if [[ $num -lt 10 ]]; then | |
echo -n "${ones[$num]} " | |
fi | |
} | |
export -f num_to_words | |
function do_each() { | |
AR=($@) | |
AS="" S="" | |
if [ ${AR[0]} -ne 1 ]; then AS="'s" S="s"; fi | |
echo "$( num_to_words ${AR[0]}) ${AR[1]}$S" | |
if $( command -v say ); then say "${@}$AS"; fi | |
} | |
export -f do_each | |
# check input | |
ARGC="$#" | |
if [[ "$ARGC" -ne 1 ]]; then | |
echo "Please enter an integer number, e.g. 123" | |
exit 1 | |
fi | |
STR="$1" | |
re='^[0-9]+$' | |
if ! [[ $STR =~ $re ]] ; then | |
echo "error: Not a number" >&2; exit 1 | |
fi | |
# iterate through input | |
grep -o . <<< "$STR" | sort | uniq -c | xargs -I J bash -c "do_each J" |
Author
smartwatermelon
commented
Aug 29, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment