-1

cannot find the problem, everytime when I'm running this code it goes stackoverflow due to this line

countCombine += count(array,money - (array[i]*(int)(money/array[i])));

basically problem is very easy. Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn’t matter.

For example, for N = 4 and S = {1,2,3}, there are four solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}. So output should be 4. For N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. So the output should be 5.

    public class CoinExchangeProblem {

        int countCombine = 0;
        private int count(int array[],int money){
    //        sort the array 
    //        Arrays.sort(array);    
    //        System.out.println(Arrays.toString(array));


            if (money == 0) {
                return 1;
            } else if (money < 0) {
                return 0;
            }


            for(int i = 0; i < array.length; i++){
                countCombine += count(array,money - (array[i]*(int)(money/array[i])));
            }
            return countCombine;

        }




        public static void main(String[] args) {
            CoinExchangeProblem coinExch = new CoinExchangeProblem();
            System.out.println(coinExch.count(new int[]{1,2,3}, 4));
    //        System.out.println(coinExch.count(new int[]{2, 5, 3, 6}, 10));
        }
}
gauravds
  • 2,931
  • 2
  • 28
  • 45
  • Have you run this in an IDE debugger? If not, do so ASAP. – Jim Garrison Jul 13 '13 at 03:17
  • yes I tried the debugger and I think "for(int i = 0;" this is the cause of problem. – gauravds Jul 13 '13 at 03:25
  • You must do more `if (money < 0)` than just return 0, you need to change what the program does including having it try a coin of another value. But more importantly, the logic of your recursion must be thought out and tested on paper before trying to commit it to code. Also you need to find a way to either return multiple solutions or print out multiple solutions. – Hovercraft Full Of Eels Jul 13 '13 at 03:38
  • And in fact, your logic completely escapes me, and I don't see how it will come close to solving your problem. Have you worked this out on paper first? – Hovercraft Full Of Eels Jul 13 '13 at 03:51

1 Answers1

2

When this part

(array[i]*(int)(money/array[i]))

equals zero your are a victim of infinite recursion where you are calling the function with the same amount of money

You can change it to :

 if(money >= array[i])
        countCombine += count(array,money - (array[i]*(int)(money/array[i])));

so you will never get a zero here, but test it for more examples as i didn't test it a lot , but I think that it is logically right

Sara Tarek
  • 369
  • 3
  • 13