while loop - Java recursion class variable value is reset to 0 -
i trying implement coin change problem using recursion. have written following code , facing problem static class variable. 'answer' class variable , trying add return value in loop. works fine within while loop after while loop ends answer reset 0;
while (i * currentcoin <= sum) { system.out.println("inside while; answer " + answer); answer = answer + findcombinations( sum - * currentcoin, new arraylist<integer>(denominations.sublist(1, denominations.size()))); i++; }
below code have written. can copy , run check.
import java.util.arraylist; import java.util.collections; public class coinchangehashmap { static int answer = 0; public static void main(string[] args) { int[] array = new int[] { 7, 3, 2 }; arraylist<integer> input = new arraylist<integer>(); getlist(array, input); findcombinations(12, input); system.out.println(answer); } private static void getlist(int[] array, arraylist<integer> input) { (int : array) { input.add(i); } } public static int findcombinations(int sum, arraylist<integer> denominations) { if (denominations.size() == 1) { if (sum % denominations.get(0) == 0) { return 1; } return 0; } int = 0; int currentcoin = denominations.get(0); while (i * currentcoin <= sum) { system.out.println("inside while; answer " + answer); answer = answer + findcombinations( sum - * currentcoin, new arraylist<integer>(denominations.sublist(1, denominations.size()))); i++; } return 0; }}
**the output 0. expected output 4. while debugging output got **
inside while; answer 0 inside while; answer 0 inside while; answer 1 inside while; answer 1 inside while; answer 2 inside while; answer 2 inside while; answer 0 inside while; answer 0 inside while; answer 0 0
any appreciated.
the problem related odd code structure, in convey outcome of recursive call modifying static variable answer
, , via method's return value.
if analyzed problem more closely, discover not upon exit loop partial results lost, rather time after return method. therefore, consider way update answer:
answer = answer + findcombinations( /* ... */ );
at top-most level of recursion, answer
0
. when java evaluates above expression, evaluates first left operand , right operand, adds them. is, evaluates answer
, getting result 0
, before performs recursive call. value of answer
may updated in course of recursive call, changes come late. bottom-most level of recursion ever returns value different zero, if recursive call recurses @ least 1 level deeper return zero. in case, sum computed 0 + 0
, , assigned answer
, clobbering update method performed.
you resolve problem swapping order of operands in sum, better, , not harder, rid of static variable altogether. use local variable within method accumulate results, , in cases convey total caller via method's return value.
Comments
Post a Comment