I have an assignment in a computer architecture course whereby we are writing MI
ID: 3529858 • Letter: I
Question
I have an assignment in a computer architecture course whereby we are writing MIPS assembly using recursion. The problem is to determine and print out all the possible combinations of change that certain amount of money represents. I am trying to code up a working model in java so I can use it as a model to write the MIPS code from.
could someone assist me in populate an aray or array list or what ever data structure you'd like all that is important is for
the output to represent the actual denomination variations of a given amount of money.
Sample input of cents:
10
10 coins: 1 1 1 1 1 1 1 1 1 1
6 coins: 1 1 1 1 1 5
6 coins: 1 1 1 1 5 1
6 coins: 1 1 1 5 1 1
6 coins: 1 1 5 1 1 1
6 coins: 1 5 1 1 1 1
6 coins: 5 1 1 1 1 1
2 coins: 5 5
1 coins: 10
soultion count: 9
cal count: 101
returned from main function, DONE!
import java.util.*;
public class change2 {
ArrayList<Integer> ourList = new ArrayList<Integer>();
static int d = 0;
static int count = 0;
static int solCount = 0;
static int arrayCounter = 0;
public static void main(String[] args) {
change(10, 0,0);
System.out.println("Solution count: " + solCount);
System.out.println("Call count: " + count);
System.out.println(" Returned from main function");
}
public static void change(int remaining, int coin,int depth) {
count++;
int leftover = remaining - coin;
d = depth;
if (leftover < 0) {
return;
} else if (leftover == 0) {
solCount++;
System.out.println(depth + " coins: " + coin);
return;
} else {
change (leftover, 1, depth+1);
change (leftover, 5, depth+1);
change (leftover, 10, depth+1);
change (leftover, 25, depth+1);
}
}
}
this is very close as it accurately prints the depth soultion count and call count it just only prints 1 of the coins on the upper levels and I am after all of them like the goal.
Explanation / Answer
try this
public class CoinProblem
{
public static void main(String[] args)
{
int[] coins = {1, 3, 5, 10, 20, 50, 100, 200, 500};
int amount = new java.util.Random().nextInt(10000);
int coinsCount = 0;
System.out.println("amount = " + amount);
int[] numberOfCoins = findNumberOfCoins(coins, amount);
for (int i = 0; i < numberOfCoins.length; i++)
{
if (numberOfCoins[i] > 0)
{
System.out.println("coins= " + coins[i] + " Count=" + numberOfCoins[i] + " ");
coinsCount += numberOfCoins[i];
}
}
System.out.println("numberOfCoins = " + coinsCount);
}
private static int[] findNumberOfCoins(int[] coins, int amount)
{
int c = coins.length;
int[] numberOfCoins = new int[coins.length];
while (amount > 0)
{
c--;
if (amount >= coins[c])
{
int quotient = amount / coins[c];
amount = amount - coins[c] * quotient;
numberOfCoins[c] = quotient;
}
}
return numberOfCoins;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.