Midhun
Midhun

Reputation: 23

How to resolve variable increment issue in a recursive function

Trying to create a pascals triangle using recursive function. Returning value is always zero.

I'm new to Scala programming and not sure if the declaring the value variable in the code is the right way. Appreciate any help with the right approach. Thanks

object Main {
  def main(args: Array[String]) {
    println("Pascal's Triangle")
    for (row <- 0 to 10) {
      for (col <- 0 to row)
        print(pascal(col, row) + " ")
      println()

    }
  }

  var value: Int = 0
  def pascal(c: Int, r: Int): Int = {
    if (c ==0) 1
    else if (c == r ) 1
    else
      for (col <- c-1 to c) {
        value +=   pascal(col, r - 1)
      }
      value
    }
  }

Actual Result

Pascal's Triangle
0 
0 0 
0 0 0 
0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 0 
0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 

Expected Result

Pascal's Triangle
1 
1 1 
1 2 1 
1 3 3 1 
1 4 6 4 1 
1 5 10 10 5 1 
1 6 15 20 15 6 1 
1 7 21 35 35 21 7 1 
1 8 28 56 70 56 28 8 1 
1 9 36 84 126 126 84 36 9 1 
1 10 45 120 210 252 210 120 45 10 1

Upvotes: 0

Views: 250

Answers (2)

jwvh
jwvh

Reputation: 51271

Scala style tries to avoid mutable data (i.e. var).

def pascalTriangle(height :Int) :Unit =
  Iterator.iterate(Vector(1))(v => (0+:v:+0).sliding(2).map(_.sum).toVector)
          .take(height)          //take only as many as needed
          .map(_.mkString(" "))  //turn Vector into space separated String
          .foreach(println)      //force the calculations

Here we create an infinite collection of Vectors, each one longer than the previous. Each Vector is processed to create the required sums, but none of that happens until the foreach() because an Iterator is lazy.

Upvotes: 2

Allen Han
Allen Han

Reputation: 1163

You should avoid using var. In this case, you don't need it. Avoid var, use val. Such is good functional programming practice.

object Pascal {

  def main(args: Array[String]) {
    println("Pascal's Triangle")
    for (row <- 0 to 10) {
      for (col <- 0 to row)
        print(pascal(col, row) + " ")
      println()

    }
  }

  def pascal(c: Int, r: Int): Int = {
    if (c ==0) 1
    else if (c == r ) 1
    else {
      val intermediate = for (col <- c - 1 to c) yield pascal(col, r - 1)
      intermediate.sum
    }
  }
}

Upvotes: 1

Related Questions