The objective of my program is to output all possible change solutions to a given amount of money, for example
DESIRED OUTPUT
Change: 9
[1, 1, 1, 1, 5]
[1, 1, 1, 1, 1, 1, 1, 1, 1]
(with 9 = $0.09) However my output is a little different, my output looks like this
MY OUTPUT
Change: 9
[1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 5]
[1, 1, 1, 5, 1]
[1, 1, 5, 1, 1]
[1, 5, 1, 1, 1]
[5, 1, 1, 1, 1]
As you can see, it LITERALLY gives me all possible solutions. I only care about the top two answers. It's obvious that this will be a big problem when bigger amounts are asked for. So here's my question: Based off my code, how do I fix it to where it will only display one combination each?
CODE
import java.io.*;
import java.util.*;
import java.lang.*;
public class homework5 {
public static int change;
public static void main(String[] args)
throws FileNotFoundException { //begin main
ArrayList<Integer> coinTypes = new ArrayList<Integer>();//array to store
//coin types
ArrayList<Integer> answerCoins = new ArrayList<Integer>(); //to contain solutions
Integer i;
File f = new File (args[0]);
Scanner input = new Scanner(f); //initialize scanner
input.nextLine();
while(input.hasNextInt()) {
i = input.nextInt();
coinTypes.add(i); //add all ints to file
}
change = coinTypes.get(coinTypes.size()-1);
coinTypes.remove(coinTypes.size()-1);
System.out.println("Change: " + change);
findChange(change, coinTypes, answerCoins);
}
private static void findChange(int change, List<Integer> coinTypes,
List<Integer> answerCoins) { //contains means of
//finding the change solutions
if(change == 0) {
//base case
System.out.println(answerCoins);
}
else if(change < 0) {
//if negative it can't be a solution
} else {
for(int coin = 0; coin < coinTypes.size(); coin++) {
answerCoins.add(coinTypes.get(coin)); //choose
findChange(change-coinTypes.get(coin), coinTypes, answerCoins);//explore
answerCoins.remove(answerCoins.size()-1); //un-choose
}
}
}
}
Thank you for any and all answers, please try to overlook any other mistakes, I would like to address this question first. Thanks!!