Skip to content

Instantly share code, notes, and snippets.

@ihji
Created June 17, 2013 11:15
Show Gist options
  • Save ihji/5796195 to your computer and use it in GitHub Desktop.
Save ihji/5796195 to your computer and use it in GitHub Desktop.
Simple Pascal's triangle in Scala
object PascalTriangle extends App {
def triangle(n: Int) {
def nextList(l: List[Int]) : List[Int] =
if(l.length > 1) 1 +: l.sliding(2).toList.map{_.reduce{_+_}} :+ 1
else List(1,1)
val (result,_) = (n-1 to 0 by -1).foldLeft("",List(1)) {
case ((str,lst),space) => (str + " "*space + lst.mkString(" ") + "\n",nextList(lst))
}
print(result)
}
triangle(args(0).toInt)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment