• + 0 comments

    My solution in scala. Because of restriction in not using local variables, some computations were repeated.

    import scala.io.StdIn
    import scala.annotation.tailrec
    
    object Solution {
    
      def drawTrees(n: Int): Unit = {
        def recursiveTrees(n: Int, pHeight: Int, root: Int, base: Int, arr: Array[Array[Char]]): Array[Array[Char]] = {
          if (n > 0) {
            for (i <- Range(base, base-pHeight, -1)) {
              arr(i)(root) = '1'
            }
            @tailrec
            def fill_branch(i: Int, j: Int, x:Int, counter: Int): Unit = {
              if (counter != 0) {
                arr(x)(i) = '1'
                arr(x)(j) = '1'
                fill_branch(i-1, j+1, x-1, counter-1)
              }
            }
            fill_branch(root-1, root+1, base-pHeight, pHeight)
            recursiveTrees(n-1, pHeight/2, root-pHeight, base-(pHeight*2), arr)
            recursiveTrees(n-1, pHeight/2, root+pHeight, base-(pHeight*2), arr)
          }
          return arr
        }
        recursiveTrees(n, 16, 49, 62, Array.fill(63, 100)('_')).foreach(row => println(row.mkString))
      }
    
      def main(args: Array[String]) {
          drawTrees(StdIn.readInt())
      }
    }