-
Notifications
You must be signed in to change notification settings - Fork 0
/
min_coins.cpp
80 lines (71 loc) · 2.05 KB
/
min_coins.cpp
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
71
72
73
74
75
76
77
78
79
80
// Greedy algorithm
#include <iostream> // std::cout
#include <concepts> // for std::integral
#include <array> // for std::array
#include <vector> // for std::vector
#include <algorithm> // for std::sort
static constexpr std::size_t INPUT_SIZE = 140;
static constexpr std::array<std::size_t, 4> gCoins = { 10, 5, 15, 100 };
auto GetLargestSmallEql(auto beginIt, auto endIt, auto value) noexcept
{
for(auto it = beginIt; it != endIt; it++)
{
if(*it <= value)
return it;
}
return endIt;
}
template<std::integral auto NCoins>
static void _getMinCoins(std::array<std::size_t, NCoins>& coins, std::integral auto sum, std::vector<std::size_t>& minCoins) noexcept
{
// Find the largest coin which is equal to 'sum' or less than 'sum'
auto it = GetLargestSmallEql(coins.begin(), coins.end(), sum);
if(it != coins.end())
{
auto coinValue = *it;
while(sum >= coinValue)
{
minCoins.push_back(coinValue);
sum -= coinValue;
}
_getMinCoins(coins, sum, minCoins);
}
}
template<std::integral auto NCoins>
static std::vector<std::size_t> getMinCoins(std::array<std::size_t, NCoins> coins, std::integral auto sum) noexcept
{
// Sort the given coins in decreasing order - meaning the highest value coin comes first (at index 0)
std::sort(coins.begin(), coins.end(), std::greater { });
std::vector<std::size_t> minCoins;
_getMinCoins(coins, sum, minCoins);
return minCoins;
}
template<typename T>
concept ArrayLikeContainer = requires(T& cont)
{
{ cont.size() } -> std::integral;
cont.begin();
cont.end();
};
template<ArrayLikeContainer T>
static std::ostream& operator<<(std::ostream& stream, const T& array) noexcept
{
stream << "{ ";
for(decltype(array.size()) i = 0; auto& value : array)
{
stream << value;
if((i + 1) != array.size())
stream << ", ";
++i;
}
stream << " }";
return stream;
}
int main()
{
std::cout << "Given Coins: " << gCoins << "\n";
std::cout << "Given Sum: " << INPUT_SIZE << "\n";
std::vector<std::size_t> minCoins = getMinCoins(gCoins, INPUT_SIZE);
std::cout << "Minimum Number of Coins: " << minCoins << std::endl;
return 0;
}