Created
November 14, 2015 21:01
-
-
Save rtfpessoa/54607e7a3e002929d1a5 to your computer and use it in GitHub Desktop.
LittleTree Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.rtfpessoa.scala | |
import scala.language.postfixOps | |
import scala.util.Properties | |
case class LittleTree(height: Int) { | |
implicit class IntOps(int: Int) { | |
def isOdd = int % 2 > 0 | |
} | |
private def makeTree: String = { | |
repeatLine(height) { line => | |
times(height - line - 1)(" ") + | |
times(2 * line - 2)("*") | |
} | |
} | |
private def makeTrunk: String = { | |
val lastLineWidth = height * 2 - 1 | |
if (height.isOdd) { | |
repeatLine(height / 2) { line => | |
times(lastLineWidth / 4 - 1)(" ") + | |
times(lastLineWidth / 2)("#") | |
} | |
} else { | |
repeatLine(height / 2) { line => | |
times(lastLineWidth / 4)(" ") + | |
times(lastLineWidth / 2 - 1)("x") | |
} | |
} | |
} | |
private def repeatLine(limit: Int)(body: Int => String): String = { | |
0 to limit map body mkString Properties.lineSeparator | |
} | |
private def times(limit: Int)(body: => String): String = { | |
0 to limit map (_ => body) mkString | |
} | |
override def toString: String = { | |
Seq(makeTree, makeTrunk) mkString Properties.lineSeparator | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment