I have made an implementation of the pascal's triangle but something is wrong with it since when col match { case row => ...}
it doesn't correctly match the col with the row:
def main(args: Array[String]) {
println("Pascal's Triangle")
for (row <- 0 to 10) {
for (col <- 0 to row) {
val res: Int = pascal(col, row)
print(res + " ")
}
println()
}
def pascal(col: Int, row: Int): Int = {
col match {
case 0 => 1
case row => 1
case _ => pascal(col-1, row-1) + pascal(col, row-1)
}
}
Your row
match is shadowing the method parameter. To achieve what you want, you could try to use so called guards for your pattern match, e.g.
case n if n == row => 1
With this, you have 3 cases, the 0
case, the case when n is equal to given row parameter
and the default
case. Otherwise, the row
match would match all remaining numbers not equal to 0
, which will leave the _
match at the end never be triggered.