Problem Statement
A description of the problem can be found on Hackerrank.
Solution
I created recursive function for factorial
.
Then create all combinations of rows and column indexes. For input 4
it looks like:
1 2 3 4 |
(0,0) (1,0), (1,1) (2,0), (2,1), (2,2) (3,0), (3,1), (3,2), (3,3) |
Apply function for pascal triangle
for each combination.
I created solution in Scala:
The solution is also available on my GitHub.
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
object PascalTriangle extends App { val k = io.Source.stdin.bufferedReader().readLine().toInt (0 until k).foreach { row => println(List.range(0, row + 1) .map(col => fact(row) / (fact(col) * fact(row - col))) .mkString(" ")) } def fact(n: Int): Int = { if(n <= 1) 1 else n * fact(n - 1) } } |