Functions and Fractals - Recursive Trees - Bash!

  • + 0 comments

    ITERATIVE version (ultra-compact)

    • If you know how to format the code better on this broken editor, please let me know.
    • If there is a way to update my submitted answer, please let me know
    • *
    #!/bin/bash
    read tree_depth
    xpos=(50) # Roots where we start the Ys
    for ((y=1; y<=63; y++)); do
      for ((x=1; x<=100; x++)); do
        char=_
          if (( tree_depth > printed )); then # if we need more depth
            length=$((2**(4-printed))) b=y-offset-length
            # b is the y coordinate from the point of view of the center of the Y we are drawing
            if (( b <= length )); then
              (( b < 0 )) && b=0 # Force vertical (to draw a Y instead of an X)
              for p in "${xpos[@]}"; do
                if (( p-b == x || p+b == x )); then
                  char=1
                  # If b == length, we are finishing drawing this rank's Ys
                  # So we save the x position for future Y roots
                  (( b == length )) && new_xpos+=("$x")
                fi
              done
            fi
          fi
        printf %s "$char"
      done
      if (( b == length )); then
        # We finished drawing the Ys for this level
        # We set the new roots and the offset for coordinate computation
        xpos=("${new_xpos[@]}") new_xpos=() printed=$((printed+1)) offset=$y
      fi
      echo
    done | tac