-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathGreedy Change-Making Algorithm.cpp
More file actions
70 lines (56 loc) · 1.77 KB
/
Copy pathGreedy Change-Making Algorithm.cpp
File metadata and controls
70 lines (56 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
using namespace std;
void change(int[], int[], int, int);
int main()
{
int changeQuant;
int numDenom;
// Dynamically allocated data allows the user to enter
// any number of coin denominations.
int* coinDenom;
int* numCoins;
cout << "\n Enter the number of coin denominations: ";
cin >> numDenom;
coinDenom = new int[numDenom]; // Array holding the values of the coin denominations
numCoins = new int[numDenom]; // Array holding the number of coins per denomination
cout << "\n Enter the values for coin denominations, "
<< "\n in order of decreaing value.\n";
// Loop runs for the number of coin denominations entered and
// receives the value of each coin denomination
for (int i = 0; i < numDenom; i++)
{
cout << "\n Enter the value for coin denomination " << (i + 1) << ": ";
cin >> coinDenom[i];
}
cout << "\n Enter a positive value of change to receive, in cents: ";
cin >> changeQuant;
change(coinDenom, numCoins, changeQuant, numDenom);
cout << "\n The change is as follows: \n";
// Loop displays the number of coins per denomination
for (int i = 0; i < numDenom; i++)
{
// Will only display the number of coins if coins are greater than 0
if (numCoins[i] > 0)
{
cout << "\n\t " << coinDenom[i] << "-cent coins: "
<< numCoins[i];
}
}
return 0;
}
// Greedy algorithm.
void change(int cd[], int nc[], int cq, int nd)
{
for (int i = 0; i < nd; i++)
{
int coinCount = 0; // The variable counts the number of coins.
while (cq >= cd[i])
{
coinCount++; // Adds one coin
cq = cq - cd[i]; // Remaining amount of change
}
// Stores the number of coins for the current denomination
// in the numCoins array.
nc[i] = coinCount;
}
}