Last active
December 14, 2021 23:11
-
-
Save smartwatermelon/a00650ec0f271e6f951758d7a3481ea4 to your computer and use it in GitHub Desktop.
@cassidoo's interview question from December 12, 2021
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 | |
| # Given a file named merry-christmas.txt that has a single integer x in it, write a script | |
| # to generate a Christmas tree with asterisks (*) and output it as happy-holidays.txt. The | |
| # tree should have a height of x, and if merry-christmas.txt is empty, the height should | |
| # be 25 asterisks tall. | |
| IN_FILE="merry-christmas.txt" | |
| OUT_FILE="happy-holidays.txt" | |
| if ! [ -f ${IN_FILE} ]; then | |
| echo "Can't find ${IN_FILE}" | |
| exit 1 | |
| fi | |
| if [ -f ${OUT_FILE} ]; then | |
| read -p "${OUT_FILE} exists, overwrite? " -n 1 -r | |
| echo | |
| if [[ ! $REPLY =~ ^[Yy]$ ]]; then | |
| exit 1 | |
| fi | |
| :>${OUT_FILE} | |
| fi | |
| read -r lines < ${IN_FILE} || : | |
| if [ -v $lines ] || ! [[ $lines =~ ^[0-9]+$ ]]; then | |
| lines=25 | |
| fi | |
| for ((row=1; row<=$lines; row++)); do | |
| num_spaces=$((lines-row)) | |
| num_stars=$(((2 * row) -1)) | |
| printf -v row_spaces '%*s' $num_spaces | |
| printf -v row_stars '*%.0s' $(seq 1 $num_stars) | |
| echo "${row_spaces}${row_stars}" >> ${OUT_FILE} | |
| done | |
| if [ $# -gt 0 ]; then | |
| if [ "$1" == "base" ]; then | |
| num_spaces=$((lines-1)) | |
| printf -v pole_spaces '%*s' $num_spaces | |
| echo "${pole_spaces}|" >> ${OUT_FILE} | |
| base_length=$((lines / 2)) | |
| if [ $(( base_length % 2)) ]; then ((base_length++)); fi | |
| num_spaces=$(((num_stars - base_length) / 2 )) | |
| printf -v base_spaces '%*s' $num_spaces | |
| printf -v base '=%.0s' $(seq 1 $base_length) | |
| echo "${base_spaces}${base}" >> ${OUT_FILE} | |
| fi | |
| fi | |
| echo | |
| cat ${OUT_FILE} |
Author
smartwatermelon
commented
Dec 14, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment