Created
April 3, 2023 18:28
-
-
Save smartwatermelon/ab9b5886128e9120b1ad3deebb2f320f to your computer and use it in GitHub Desktop.
@cassidoo's interview question from April 2, 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 | |
| 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 | |
| } | |
| # Call the function with this script as the argument | |
| num_to_words $( wc -m $0 ) |
Author
smartwatermelon
commented
Apr 3, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment