How to resolve the algorithm Pascal's triangle step by step in the Scala programming language
How to resolve the algorithm Pascal's triangle step by step in the Scala programming language
Table of Contents
Problem Statement
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be: So the triangle now looks like this: Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for n ≤ 0 does not need to be uniform, but should be noted.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Pascal's triangle step by step in the Scala programming language
Source code in the scala programming language
def tri(row: Int): List[Int] =
row match {
case 1 => List(1)
case n: Int => 1 +: ((tri(n - 1) zip tri(n - 1).tail) map { case (a, b) => a + b }) :+ 1
}
def prettyTri(n:Int) = (1 to n) foreach {i => print(" "*(n-i)); tri(i) map (c => print(c + " ")); println}
prettyTri(5)
object Blaise extends App {
def pascalTriangle(): Stream[Vector[Int]] =
Vector(1) #:: Stream.iterate(Vector(1, 1))(1 +: _.sliding(2).map(_.sum).toVector :+ 1)
val output = pascalTriangle().take(15).map(_.mkString(" "))
val longest = output.last.length
println("Pascal's Triangle")
output.foreach(line => println(s"${" " * ((longest - line.length) / 2)}$line"))
}
You may also check:How to resolve the algorithm Factorial step by step in the Scilab programming language
You may also check:How to resolve the algorithm Find limit of recursion step by step in the R programming language
You may also check:How to resolve the algorithm Real constants and functions step by step in the Elena programming language
You may also check:How to resolve the algorithm XML/Output step by step in the MATLAB programming language
You may also check:How to resolve the algorithm Optional parameters step by step in the Mathematica/Wolfram Language programming language