We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
base_str="________________________________________________________________________________________________"
declare -a str_arr
Read input level
read level
Recursive function to draw fractal tree
draw_fractal() {
local current_level=2
local pos=4
# Base case: Stop recursion when max level is reached
if [ "`$current_level" -eq "$`level" ]; then
return
fi
# Draw vertical trunk
for ((i = 0; i < row_no; i++)); do
str_arr[`$row_current]="$`{str_arr[`$row_current]:0:$`pos}1`${str_arr[$`row_current]:`$(($`pos + 1))}"
row_current=$((row_current + 1))
done
# Draw left and right diagonal branches
for ((i = 1; i <= row_no; i++)); do
str_arr[`$row_current]="$`{str_arr[`$row_current]:0:$`((`$pos + i))}1$`{str_arr[`$row_current]:$`(($pos + i + 1))}"
str_arr[`$row_current]="$`{str_arr[`$row_current]:0:$`((`$pos - i))}1$`{str_arr[`$row_current]:$`(($pos - i + 1))}"
row_current=$((row_current + 1))
done
# Recursively draw left and right subtrees
draw_fractal `$((current_level + 1)) $`((row_no / 2)) `$((pos - row_no)) $`row_current
draw_fractal `$((current_level + 1)) $`((row_no / 2)) `$((pos + row_no)) $`row_current
}
Initialize the grid with underscores (_)
for ((i = 0; i < 63; i++)); do
str_arr[base_str
done
Start drawing from the bottom center
draw_fractal 0 16 49 0
Print the grid from bottom to top
for ((i = 62; i >= 0; i--)); do
echo "${str_arr[i]}"
done
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Functions and Fractals - Recursive Trees - Bash!
You are viewing a single comment's thread. Return to all comments →
!/bin/bash
Define the base empty row
base_str="________________________________________________________________________________________________" declare -a str_arr
Read input level
read level
Recursive function to draw fractal tree
draw_fractal() { local current_level=2 local pos=4
}
Initialize the grid with underscores (_)
for ((i = 0; i < 63; i++)); do str_arr[base_str done
Start drawing from the bottom center
draw_fractal 0 16 49 0
Print the grid from bottom to top
for ((i = 62; i >= 0; i--)); do echo "${str_arr[i]}" done