Java coin change outputting weird values [Not homework] -
i'm trying coin change algorithm work... it's outputting weird results... it's supposed enumerate permutations of change given input amount of cents.
input of 27 cents, printvalues(dan.makechange(27));
gets me:
[[3, 300, 1386, 4720], [3, 300, 1386, 4720], [3, 300, 1386, 4720],etc...
input of 7 cents gets me:
[[0, 0, 3, 10], [0, 0, 3, 10], [0, 0, 3, 10], [0, 0, 3, 10]]
code:
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 list... resultslist.add(toadd); return resultslist; } int[] coins = {25, 10, 5, 1}; (int = 0; < coins.length; i++) { if (coins[i] <= change) { //temp = {0, 0, 0, 0} int[] temp = toadd; //move next amount in temp array temp[i]++; resultslist = changemaker(change-coins[i], temp, resultslist); } } return resultslist; }
call:
printvalues(dan.makechange(27)); } public void printvalues (list<int[]> results) { list<string> printable = new arraylist<string> (); (int[] array : results) { printable.add(arrays.tostring(array)); } system.out.println(printable); }
any thoughts?
i assume wanted copy array line:
int[] temp = toadd;
however, create copy, have this:
int[] temp = arrays.copyof(toadd, toadd.length);
Comments
Post a Comment