Functions and Fractals - Recursive Trees - Bash!

  • + 0 comments

    EZ

    #!/bin/bash
    base_str="____________________________________________________________________________________________________"
    str_arr=()
    read level
    draw_fractal() {
        local current_level=$1
        local row_no=$2
        local pos=$3
        local row_current=$4
        if [ $current_level -eq $level ]; then
            return
        fi
        for ((i = 1; 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
        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
        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
    }
    for (( i=1; i<=64; i++ )); do
        str_arr[i]=$base_str
    done
    
    draw_fractal 0 16 49 1
    
    length=${#str_arr[@]}
    for (( i=length-1; i>=0; i-- )); do
        echo "${str_arr[i]}"
    doner_arr[i]}"
    done