Ticket Machine

suggest change

Consider a simple example.

A ticket machine returns change using coins with values 1, 2, 5, 10, and 20. Returning change is a series of coin drops until the correct amount has been dispensed. A selection of coins is optimal when it uses the fewest coins for that amount.

Let M in [1, 50] be the ticket price and P in [1, 50] be the amount paid, where P >= M. The required change is D = P - M. At each step, dispensing a coin with value c reduces the remaining change from D to D - c.

The greedy approach repeatedly dispenses the largest coin that does not exceed the remaining change:

  1. While D >= 20, dispense a 20-value coin and subtract 20 from D.
  2. While D >= 10, dispense a 10-value coin and subtract 10 from D.
  3. Continue in the same way for coins with values 5, 2, and 1.

The dispensed coins sum to the original required change. This is a greedy algorithm because each step chooses the largest currently valid coin.

Here is the ticket-machine algorithm in modern C++:

#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>

std::vector<unsigned int> readCoinValues();

int main()
{
    const std::vector<unsigned int> coinValues = readCoinValues();
    int ticketPrice;
    int paidMoney;
    
    std::cout << "ticket price: ";
    std::cin >> ticketPrice;
    
    std::cout << "money paid: ";
    std::cin >> paidMoney;
    
    if (paidMoney < ticketPrice) {
        std::cerr << "The amount paid is less than the ticket price.\n";
        return 1;
    }
    
    int remaining = paidMoney - ticketPrice;
    std::vector<unsigned int> coinCount;
    coinCount.reserve(coinValues.size());
    
    for (const unsigned int coinValue : coinValues) {
        coinCount.push_back(remaining / coinValue);
        remaining %= coinValue;
    }
    
    std::cout << "the difference " << paidMoney - ticketPrice
              << " is paid with:\n";
    
    for (std::size_t i = 0; i < coinValues.size(); ++i) {
        if (coinCount[i] > 0) {
            std::cout << coinCount[i] << " coin(s) with value "
                      << coinValues[i] << '\n';
        }
    }
    
    return 0;
}

std::vector<unsigned int> readCoinValues()
{
    // Including 1 guarantees that every nonnegative amount can be returned.
    std::vector<unsigned int> coinValues{1};

    while (true) {
        int coinValue;
        std::cout << "Coin value (<1 to stop): ";
        if (!(std::cin >> coinValue) || coinValue < 1) {
            break;
        }
        coinValues.push_back(static_cast<unsigned int>(coinValue));
    }
    
    std::ranges::sort(coinValues, std::greater{});
    const auto duplicates = std::ranges::unique(coinValues);
    coinValues.erase(duplicates.begin(), duplicates.end());
    
    std::cout << "Coin values: ";
    for (const unsigned int value : coinValues) {
        std::cout << value << ' ';
    }
    std::cout << '\n';
    
    return coinValues;
}

Input validation beyond detecting nonnumeric coin input is omitted to keep the example focused. One example output is:

Coin value (<1 to stop): 2
Coin value (<1 to stop): 4
Coin value (<1 to stop): 7
Coin value (<1 to stop): 9
Coin value (<1 to stop): 14
Coin value (<1 to stop): 4
Coin value (<1 to stop): 0
Coin values: 14 9 7 4 2 1 
ticket price: 34
money paid: 67
the difference 33 is paid with: 
2 coins with value 14
1 coins with value 4
1 coins with value 1

As long as 1 is among the coin values, the algorithm returns all of the required change because:

However, greedy coin selection has an important limitation:

At each step the algorithm makes a locally optimal choice, but that does not guarantee a globally optimal result for arbitrary coin systems. The greedy method is optimal for many canonical currency systems, but not for every possible set of denominations.

For example, with coin values 1, 3, 4 and D = 6, the optimal solution uses two 3-value coins. The greedy algorithm instead chooses 4, then two 1-value coins, using three coins. A dynamic programming algorithm can find an optimal solution for arbitrary denominations.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents