# On the Change Making Problem

# Mailing Matter with Stamps

I’ve developed a recent appreciation for stamps thanks to the postal system’s low rates for mailing out large envelopes. I would just print out online shipping labels, but neither the USPS nor PayPal’s multi-order shipping tool let you buy labels for the first-class large envelope rate. And while I *could* just use the regular package rate with free services (and before you ask, stamps.com, et al. are non-free), I’d be stuck paying a higher rate.

Fortunately for all folks interested in things philatelic, stamps are denominated in a variety of values and purchasable online from the USPS Postal Store. I’ve got a range of stamps valued anywhere from a penny to a $1.50. (It is regrettable that there are no current issues of any stamps valued at $3.50.)

# Why making change in the US is different than stamps

Suppose for a moment that you had 12 different postage stamps and wanted to run through all combinations of four stamps that you could put on the front of an envelope. You’d have to make 1365 combinations. If you were to pick any five, that’s 4368 possibilities. Once you hit six, that’s 12,376. (These numbers are given by *n* choose *r* for folks that remember their discrete math.) The numbers blow up really fast. Why is this relevant? Can’t you just pick stamps in the same way you make change?

As it turns out, you can’t. Being able to make change by starting with the largest amount first and moving down if there is any remainder is a deliberate currency design. Many countries, the US included, use a 1-2-5 series for denominating currency values. This means that the greedy solution (starting with the biggest value first) for giving change is actually the optimal one.

While the 1-2-5 series has properties that are useful for money, those properties are less useful for mail. The USPS generally issues values of stamps in a way that only require you to use a single stamp for most types of mail such as letters or postcards. Those values are less useful when you want to mail something that’s calculated, like a package or large envelope.

Take for example, mailing a 4.5oz large envelope. Depending on where you’re mailing it, at today’s prices it might cost $1.82. If I were to use the same approach to pick stamps that I’d use for money, then I’d end up with a $1.15 stamp, a 49¢ stamp, a 10¢ stamp, a 5¢ stamp and a 3¢ stamp. That’s five stamps. If I look carefully, then I can get away with only four stamps: $1.00, 70¢, 10¢ and 2¢.

Tools like the one on Fancyham use the same method as picking money, which means that I’d only ever get minimum number of stamps by coincidence. So how do I find smaller sets of stamps that still work?

# Depth-first Non-Greedy Search

As it turns out, solving that is known as the Change-making problem. On first blush, it sounds pretty easy. I started off with some Python that looked like this, courtesy of this stack overflow thread:

```
1 def minimum_coins(coin_list, offset, target_value):
2 if target_value == 0:
3 return 0
4 elif i == -1 or target_value < 0:
5 return float('inf')
6 else:
7 return min(
8 minimum_coins(coin_list, offset-1, target_value),
9 1 + minimum_coins(coin_list, offset, target_value - coin_list[offset])
10 )
11
12 def minimum_change(coin_list, target_value):
13 return minimum_coins(len(coin_list) - 1, target_value)
```

This approach worked pretty well for small values of the target value and lists of coins, but I got about 20 minutes into a run with my list of stamps before I gave up on waiting. The problem here is that this code is doing a depth-first search and makes no attempt to cull out paths that it has already visited.

# Breadth-first Non-Greedy Search

I was reading about using dynamic programming approach to solve the problem here, but I wasn’t really a fan of building a table for every possible value up to the amount that I want to find. The code there is pretty fast and did solve my problem, but it wasn’t satisfying.

The call-tree graphic on the page got me thinking that this would be a pretty easy breadth-first search to do. The great thing about the breadth-first search is that once I’ve found a level with a solution and explored all of that level, I’m guaranteed to one or more optimal answers.

The general idea is that we start off from the top of a tree with the end value (in this case, 182 cents) and dynamically create nodes that subtract from that value for each level. Once we hit zero, we know we’ve found a valid combination of stamps. So on the first level, we’d expect to see something like this:

```
1 {'target': 181, 'combo': [1]}
2 {'target': 180, 'combo': [2]}
3 {'target': 179, 'combo': [3]}
4 {'target': 178, 'combo': [4]}
5 {'target': 177, 'combo': [5]}
6 {'target': 172, 'combo': [10]}
7 {'target': 161, 'combo': [21]}
8 {'target': 148, 'combo': [34]}
9 {'target': 133, 'combo': [49]}
10 {'target': 112, 'combo': [70]}
11 {'target': 82, 'combo': [100]}
12 {'target': 67, 'combo': [115]}
```

We then iterate through those combinations until we get somewhere interesting (or don’t find anything):

```
1 {'target': 178, 'combo': [1, 1, 1, 1]}
2 {'target': 177, 'combo': [1, 1, 1, 2]}
3 {'target': 176, 'combo': [1, 1, 1, 3]}
4 {'target': 175, 'combo': [1, 1, 1, 4]}
5 {'target': 174, 'combo': [1, 1, 1, 5]}
6 {'target': 169, 'combo': [1, 1, 1, 10]}
7 {'target': 158, 'combo': [1, 1, 1, 21]}
8 {'target': 145, 'combo': [1, 1, 1, 34]}
9 ...
10 {'target': 0, 'combo': [2, 10, 70, 100]}
```

What’s that code look like?

```
1 from sets import Set
2
3 def search(coin_list, target_value, combo=[]):
4 # Make sure the list is unique and sorted
5 coins = list(set(coin_list))
6 coins.sort()
7
8 # Generate a key from each combination and store
9 # here to avoid revisiting combinations that have
10 # already been seen.
11 seencombos = set()
12
13 # Let the initial maximum level be infinity for
14 # ease of comparison.
15 maxlevel = float('inf')
16
17 # Once we've found the max level, squirrel away
18 # every solution that we find into here.
19 solutions = []
20
21 # Use a list like a queue for keeping track of what to explore.
22 next_items = []
23
24 # Initially seed
25 for coin in coins:
26 newcombo = list(combo)
27 newcombo.append(coin)
28 next_items.append({
29 'combo': newcombo,
30 'target': target_value - coin
31 })
32
33 # Look for solutions while we still have things to explore
34 while (next_items):
35 # Grab an item to examine
36 item = next_items.pop(0)
37
38 # We've exceeded the level at which we'll accept solutions, so
39 # go ahead and return all the valid ones.
40 if (len(item['combo']) > maxlevel):
41 return solutions
42
43 # Did the item hit the target value? We've found the optimal level!
44 if (item['target'] == 0):
45 # Make a note of the depth in which we found the solution
46 depth = len(item['combo'])
47 if maxlevel > depth:
48 maxlevel = depth
49
50 # Record this as a valid solution
51 solutions.append(item)
52
53 # Looks like there's still more to go.
54 # Don't bother with items that that overshot the target
55 elif (item['target'] > 0):
56
57 # Add more combos to explore
58 for coin in coins:
59 newcombo = list(item['combo'])
60 newcombo.append(coin)
61 newcombo.sort()
62
63 # Build a key like "34-49-49" for checking
64 # if we've seen this combination
65 combokey = '-'.join(str(val) for val in newcombo)
66
67 # Make sure we haven't seen this grouping before adding
68 if combokey not in seencombos:
69 seencombos.add(combokey)
70 next_items.append({
71 'combo': newcombo,
72 'target': item['target'] - coin
73 })
74
75 def find_minimum_match(coin_list, target_value):
76 current_target = target_value
77 while(True):
78 result = search(coin_list, current_target)
79 if result is None:
80 current_target = current_target + 1
81 else:
82 return result
83
84 print find_minimum_match(
85 [115, 100, 70, 49, 34, 21, 10, 5, 4, 3, 2, 1],
86 182
87 )
```

A run looks like this:

```
1 [
2 {'target': 0, 'combo': [2, 10, 70, 100]},
3 {'target': 0, 'combo': [21, 21, 70, 70]}
4 ]
```

Which are the two optimal solutions given the stamps that I have on hand. Woohoo!