Functions and Fractals - Recursive Trees - Bash!

  • + 0 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

    # 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