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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…