我試圖讓我的硬幣更改算法工作...但它輸出奇怪的結果... 它應該枚舉變化的所有排列給予輸入美分。Java硬幣更改輸出奇怪的值[不是作業]
的27美分輸入,printValues(dan.makeChange(27));
讓我:
[[3, 300, 1386, 4720], [3, 300, 1386, 4720], [3, 300, 1386, 4720],etc...
的7美分輸入打動了我:
[[0, 0, 3, 10], [0, 0, 3, 10], [0, 0, 3, 10], [0, 0, 3, 10]]
代碼:
public List<int[]> makeChange(int change) {
List<int[]> resultsList = new ArrayList<int[]>();
resultsList = changeMaker(change, new int[] {0,0,0,0}, resultsList);
return resultsList;
}
public List<int[]> changeMaker(int change, int[] toAdd, List<int[]> resultsList) {
if (change == 0) {
//if no $, return the list...
resultsList.add(toAdd);
return resultsList;
}
int[] coins = {25, 10, 5, 1};
for (int i = 0; i < coins.length; i++) {
if (coins[i] <= change) {
//temp = {0, 0, 0, 0}
int[] temp = toAdd;
//move to next amount in temp array
temp[i]++;
resultsList = changeMaker(change-coins[i], temp, resultsList);
}
}
return resultsList;
}
致電:
printValues(dan.makeChange(27));
}
public void printValues (List<int[]> results) {
List<String> printable = new ArrayList<String>();
for (int[] array : results) {
printable.add(Arrays.toString(array));
}
System.out.println(printable);
}
有什麼想法?
用調試器中運行它,看到它與預期的輸出不同。 – 2013-05-13 20:07:06