Functions and Fractals - Recursive Trees - Bash!

  • + 0 comments

    it took me almost 3.5h unexpected to solve this in office before my head blow up. i commit this bad try to view some greater solution, but all with array or/and recursive. i only formaliar with old version busybox on embeded platform, which often disable some features like array. it blocks my mind.

    here is my solution, not beautified.

    showStepY() {
        local WIDTH="$1"; shift
        local LEVEL="$1"; shift
        local CHAR="$1"; shift
        local MAXLEVEL=0
        local MAXSIZE=1
        local SIZE=1
        local REPEAT=1
        while [ $(($MAXSIZE*2)) -lt "$WIDTH" ]; do
            MAXSIZE=$(($MAXSIZE*2))
            MAXLEVEL=$(($MAXLEVEL+1))
            if [ "$MAXLEVEL" -le "$LEVEL" ]; then
                SIZE=$(($SIZE*2))
            else
                REPEAT=$(($REPEAT*2))
            fi
        done
        local INDENT=$(( ($WIDTH-$MAXSIZE)/2 ))
        local LINES=$(($SIZE/2))
        {
            if [ "$LINES" -gt 0 ]; then
                for i in `seq 0 $(($LINES-1))`; do
                    printf '%*s' $INDENT ''
                    for j in `seq 1 $(($REPEAT/2))`; do
                        printf '%*s%*s%*s' $(($SIZE/2+$i)) "$CHAR" $(($SIZE-$i*2)) "$CHAR" $(($SIZE/2+$i)) ''
                    done
                    printf '%*s\n' $(($INDENT)) ''
                done
            fi
            for i in `seq $(($SIZE-$LINES)) -1 1`; do
                printf '%*s' $INDENT ''
                for j in `seq 1 $(($REPEAT/2))`; do
                    printf '%*s%*s' $SIZE "$CHAR" $SIZE ''
                done
                printf '%*s\n' $INDENT ''
            done
        } | tr ' ' _
        return
    }
    
    showYTree() {
        local WIDTH="$1"; shift
        local MAXLEVEL="$1"; shift
        local ITER="$1"; shift
        for i in `seq 0 $MAXLEVEL`; do
            local CHAR=''
            [ $(($ITER+$i)) -le $MAXLEVEL ] || CHAR=1
            showStepY "$WIDTH" "$i" "$CHAR"
        done
    }
    
    read ITER
    showYTree 100 5 "$ITER"