AW> problem. The program is to input a value (like $1. $2. $5..)
AW> and spit out a table showing all the different cominations of coins
AW> that could be used to make up that value. So for $0.10 the table
This sounds like a problem that recursion can solve.
First, let's put all the coins in an array.
double coins[] = {0.01, 0.05, 0.10, 0.25}; //normal coins only
// or maybe just int coins[] = {1,5,10,25};
Now, we can systematically access a coin as an enumerated types.
Now, lets write only part of the problem. At each step we wish to
try to see if adding a coin will make or break the target dollar
amount.
void allCoins(double target, double tally) {
if (tally < target) {
for (int i = 0; i<4; i++) {
if (tally + coins[i] <= target) {
allCoins(target, tally + coins[i]);
}
}
}
}
The first run it will have 100 allCoins calls, each using a
penny. Next, it will have 95 pennies and a nickel, 90 pennies
and a dime, and 75 pennies and a quarter. Etc. Etc.
The REAL problem will be keeping track of which coins are
'all ready in the tally'.
I think a Stack would be the best answer.
So
Stack s;
void allCoins(double target, double tally) {
if (tally < target) {
for (int i = 0; i<4; i++) {
if (tally + coins[i] <= target) {****
s.push( coins[i] );
allCoins(target, tally + coins[i]);
s.pop();
}
}
} else if (tally == target) {
// write the contents of the stack
// assuming that Stack overloads the << operator
cout << s;
}
}
There you have it! A nice an somewhat simple solution.
--- GEcho 1.00
---------------
* Origin: Digital OnLine Magazine! - (409)838-8237 (1:3811/350)
|