Skip to content

Instantly share code, notes, and snippets.

@animatedlew
Created March 14, 2017 18:53
Show Gist options
  • Save animatedlew/c558c983f8af2e401a6655b544db887b to your computer and use it in GitHub Desktop.
Save animatedlew/c558c983f8af2e401a6655b544db887b to your computer and use it in GitHub Desktop.
object pascal {
private def get(rows: List[Long], index: Int): Long = {
if (index < 0 || index >= rows.length) 0L
else rows(index)
}
private def row(prev: List[Long] = List()): List[Long] = {
if (prev.isEmpty) List(1)
else (0 to prev.size).map { i => get(prev, i - 1) + get(prev, i) }.toList
}
def triangleRow(n: Long): List[Long] =
(0L until n).foldLeft(List.empty[Long]) { (prev, _) => row(prev) }
def triangleRows(n: Long): List[List[Long]] =
(0L until n).foldLeft(List[List[Long]]()) { (prev, _) =>
prev :+ row(prev.lastOption.getOrElse(List()))
}
def drawTriangle(n: Long): Unit = {
triangleRows(n).foreach { row =>
row.foreach { n => print(f"$n%4d") }
println
}
}
}
object Main extends App { pascal.drawTriangle(8) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment