Skip to content

Instantly share code, notes, and snippets.

@rtfpessoa
Created November 14, 2015 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rtfpessoa/54607e7a3e002929d1a5 to your computer and use it in GitHub Desktop.
Save rtfpessoa/54607e7a3e002929d1a5 to your computer and use it in GitHub Desktop.
LittleTree Implementation
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