Given a starting position k and two jump sizes d1 and d2, our task is to find the minimum number of jumps needed to reach x if it is possible.
Input : k = 10, d1 = 4, d2 = 6 and x = 8
Output : 2
1st step 10 + d1 = 14
2nd step 14 - d2 = 8
Input : k = 10, d1 = 4, d2 = 6 and x = 9
Output : -1
-1 indicates it is not possible to reach x.
My code for above problem by recursion is :
from itertools import product
def position(k, d1, d2, p, count):
count += 1
arr = [[k], ['+', '-'], [d1, d2]]
x = list(product(*arr))
for i in range(len(x)):
if x[i][1] == '+':
x[i] = x[i][0] + x[i][2]
else:
x[i] = x[i][0] - x[i][2]
if x[i] == p:
return count
for i in range(2):
position(x[i], d1, d2, p, count)
if __name__ == "__main__":
y = [int(i) for i in input().split()]
k = y[0]
d1 = y[1]
d2 = y[2]
p = y[3]
print(position(k, d1, d2, p, 0))
For input: 10 4 6 8
x = [(10,'+',4), (10,'+',6), (10,'-',4), (10,'-',6)]
After that, x = [14,16,6,4]. And count = 1. Checking if each element of x equal to 8. Now the x is recalled for 1st argument of position() as 14 & 16 like:
For 14:
x = [(14,'+',4), (14,'+',6), (14,'-',4), (14,'-',6)]
then, x = [18,20,10,8] now count become 2 and 8 is found at 4th index.
But the problem is that my code misses the recursion of 14 4 6 8 and None is printed on the console. Also, I'm not able to figure out how to return -1 if it is not possible to reach x from my position().