Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
954 views
in Technique[技术] by (71.8m points)

converting recursive function from python to scala

I'm trying to convert this recursive function from python code to scala. In python:

    def func(x,y,z):
        if x >= y:
            return 0.0
        if y>= 12:
            return 1.0/6**z
        
        probability = 0.0
        
        for val in [1,2,3,4]:
            probability += func(x,y+val,z+1)        
        for val in [5,6]:
            probability += func(x+val,y,z+1)

        return probability

    print(func(1,7,0))

In scala, my the code became

object Prob extends App {

  println(func(1, 7, 0))

  def func(y: Int, x: Int, z: Int): Double = { 
    if (x>= y) {
      return 0.0;
    }   
    if (y>= 12) {
      return scala.math.pow(1.0/6,z);
    }
      
    var probability : Double = 0.0;
      
    for (i <- 1 to 4) {
        probability += func(x,y+i,z+1);
    }
    for (i <- 5 to 6) {
        probability += func(x+i,y,z+1);
    }
    return probability;
  }
}

Unfortunately, while the python code returns the correct value of 0.6, the scala code returns 0.0.

Where's the error in the scala code?

question from:https://stackoverflow.com/questions/65858844/converting-recursive-function-from-python-to-scala

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You swapped the order of parameters:

def func(hunter,goose,num):
def func(goose: Int, hunter: Int, num: Int): Double = { 

Since you call func(1, 7, 0), in scala you immediately hit the hunter >= goose case, which returns 0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...