Reputation: 59
Can someone please tell me why I keep getting 4 when n=2 and 11 when n=3? I should be getting 3 and 7 respectively but its not happening and its very frustrating.
move is a class level static int variable
public String solve(int n, String start, String middle, String end) {
if (n == 1) {
move++;
return Integer.toString(move);
}
solve(n - 1, start, end, middle);
move++;
return solve(n - 1, middle, start, end);
}
Upvotes: 1
Views: 267
Reputation: 7730
The problem is move
is static variable and since you are not resetting it before every call so it's next time when you call solve
method, your move method is not at initial stage i.e. 0
hence you have to reinitialize it after every call to solve
method.
Your code is perfectly fine the problem is happening when you are calling your method without resetting the move variable.
Check here: https://ideone.com/NoFJ8y
Success time: 0.05 memory: 4386816 signal:0
3 --> When called solve with n=2
Success time: 0.04 memory: 4386816 signal:0
7 --> When called solve with n=3
Success time: 0.04 memory: 4386816 signal:0
3 --> When called solve 3 times with n=2 then 3 then 4
10
25
Upvotes: 3