I came up with this algorithmic problem, trying to solve the problem in my (adventure) program. There are 5 different types of coins called A, B, C, D, E (from the most valuable to the least valuable). Conversions between coin values are AtoE, BtoE, CtoE, DtoE (that is, AtoE means that a coin of type A costs AtoE to multiply by a value a coin of type E). The structure Currencyrepresents how much money the client has. Function Purpose
template <int AtoE, int BtoE, int CtoE, int DtoE>
void purchase (int numCoins, CoinType coinType, int a, int b, int c, int d, int e)
must have the client (which atype of coins a, bcoin-type b, etc.)) to buy the item, the price numCoins coinType, while minimizing the number of coins, which he received after the receipt of the change. Can someone suggest a pseudo-code for the body of this function to get the right change in order to minimize the resulting number of coins? Optimization would be nice, but first, how to make it work? I am really stuck here. Here I wrote the source code in C ++, but the problem does not depend on the language.
#include <iostream>
#include <array>
#include <algorithm>
enum CoinType {A, B, C, D, E, NumCoinTypes};
struct Currency {
std::array<int, NumCoinTypes> coins;
Currency (int a, int b, int c, int d, int e) : coins ({a,b,c,d,e}) {}
void print() const {
for (int x : coins) std::cout << x << ' ';
std::cout << " total coins = " << std::accumulate (coins.begin(), coins.end(), 0) << '\n';
}
};
struct Item {
struct Value { int numCoins; CoinType coinType; };
Value value;
};
template <int AtoE, int BtoE, int CtoE, int DtoE>
void purchase (int numCoins, CoinType coinType, int a, int b, int c, int d, int e) {
const Item item {numCoins, coinType};
Currency currency(a,b,c,d,e);
std::cout << "Before paying for the item: "; currency.print();
std::cout << "After paying for the item: "; currency.print();
}
int main() {
purchase<5,10,8,15>(50, C, 1,2,5,40,30);
}
Knapsack, , . S, , . , S - price , , . , () S, Knapsack S. , , , , S ( S). - , S - price, , , ( S S). , 1 0.
: ( ), : , . , . , , , ?
, , . , , . :
, , , .
, 4 , 5- ( , - ). . , , , , , , : , ( ), , ( ), .. , , , . , , .