As a graduate I went for an interview for a java development role and was doing pretty well in the technical examinations until i came up against this question.
If i was setting up a vending machine which (for simplicity) returned £2 change. How would i produce an implemtation that would list all the possible combinations of £2.
For e.g £1 + £1 , £1 + 50p + 50p, 50p + 50p + 50p + 50p and so on..
How could i list all the different combinations of £2.00 change possible by the vending machine.
I began to write something and this is what ive came up with so far.
Its almost working except can someone help me find out why its not expanding fully. A second pair of eyes will be grateful. And also any ways it can be optimised.
Thanks guys.
private static void printCoins(int[] tempArray) {
for (int i = 0; i < tempArray.length - 1; i++){
// to stop my array from printing out any non-denominator coins e.g
if (tempArray[i] > 0){
System.out.print(tempArray[i] + ": ");
}
System.out.println("\n");
}
}
public static void vendingMachine() {
int[] denominations = {200,100, 50, 20, 10, 5, 2, 1};
int[] tempArray = new int[50]; //combination of coins made
int total = 200;
int coinCombiIndex = 0, denomCoinIndex = 0;
// whilst all denominations havent been visited
while (denomCoinIndex < denominations.length)
// if i have the correct change
if (total - denominations[denomCoinIndex] == 0){
tempArray[coinCombiIndex] = denominations[denomCoinIndex];
denomCoinIndex++; //increment so that next iteration starts with lower denom
printCoins(tempArray); // return coins
}
// checks to see whether new total minus coin (denominator) is still >= 0
else if (total - denominations[denomCoinIndex] >= 0) {
// if so SUBTRACT from total and ADD coin to coin-combination-array
total = total - denominations[denomCoinIndex];
tempArray[coinCombiIndex] = denominations[denomCoinIndex];
coinCombiIndex++;
}
else {
denomCoinIndex++;
}
// printCoins(tempArray);
}
my output
200:
100: 100:
100: 50: 50:
100: 50: 20: 20: 10:
100: 50: 20: 20: 5: 5:
100: 50: 20: 20: 5: 2: 2: 1: