|
ADS
Algorithms and Data Structures
|
The change with the fewest coins (introduction of chapter 14). More...
Files | |
| file | ADS/optimization/CoinChange.h |
| The change with the fewest coins (introduction of chapter 14): the greedy choice takes the largest coin that fits, and is optimal for coins of 50, 10, 5 and 1 cents, but not for coins of 11, 5 and 1, where it pays 15 with five coins instead of three of 5. | |
Functions | |
| std::optional< std::vector< long > > | ADS::greedyChange (std::vector< long > coins, long c) |
| the coins taken by the greedy choice, the coins given in any order; nothing if it cannot pay | |
| std::optional< long > | ADS::optimalChange (const std::vector< long > &coins, long c) |
| the fewest coins that pay \( c \), nothing if none | |
The change with the fewest coins (introduction of chapter 14).
The definitions, the invariants and the costs of the area are in Theory of optimization.
|
inline |
the coins taken by the greedy choice, the coins given in any order; nothing if it cannot pay
In pseudocode (the example of the introduction of chapter 14), the largest coin first, as many times as it fits:
\[\class{pseudocode}{\begin{array}{r@{\quad}l} 1 & \textbf{function}\ \mathrm{greedyChange}( D , c )\quad \triangleright\ \text{optimal for some systems } D \text{ only} \cr 2 & \quad S \gets () \cr 3 & \quad \textbf{foreach}\ d \in D \text{, from the largest} \ \textbf{do}\ \text{append } \lfloor c / d \rfloor \text{ coins } d \text{ to } S;\ c \gets c \bmod d \cr 4 & \quad \textbf{return}\ S \text{ if } c = 0 \text{, else } \textbf{nil} \end{array}} \]
|
inline |
the fewest coins that pay \( c \), nothing if none
In pseudocode (beyond the book, the example of chapter 14 solved by the dynamic programming of chapter 13), the amounts by increasing value:
\[\class{pseudocode}{\begin{array}{r@{\quad}l} 1 & \textbf{function}\ \mathrm{optimalChange}( D , c ) \cr 2 & \quad N[ 0 ] \gets 0 \cr 3 & \quad \textbf{for}\ x \gets 1\ \textbf{to}\ c\ \textbf{do} \cr 4 & \qquad N[ x ] \gets \infty \cr 5 & \qquad \textbf{foreach}\ d \in D\ \textbf{with}\ d \le x\ \textbf{do} \ N[ x ] \gets \min\{ N[ x ] , N[ x - d ] + 1 \} \cr 6 & \quad \textbf{if}\ N[ c ] = \infty\ \textbf{then return nil} \cr 7 & \quad \textbf{return}\ N[ c ] \end{array}} \]