I came across a great programming article on how to calculate the combinations of states to produce 270 or more electoral college votes. I've honestly never done any dynamic programming problems like this. At least, I haven't done them the dynamic programming way; I've done them by brute force, and often I haven't gotten an answer because brute force is too slow.
With this in mind, I'll be revisiting some of the Project Euler problems because with this method and insight, so many more problems will be tractable. In particular, I expect this one will succumb to a dynamic programming solution.
In the meantime, here is the python code to solve the problem:
votes = [55, 34, 31, 27, 21, 21, 20, 17, 15, 15,
15, 13, 12, 11, 11, 11, 11, 10, 10, 10,
10, 9, 9, 9, 8, 8, 7, 7, 7, 7,
6, 6, 6, 5, 5, 5, 5, 5, 4, 4,
4, 4, 4, 3, 3, 3, 3, 3, 3, 3,
3,
]
import collections
ways = collections.defaultdict(int)
ways[0] = 1
for n in xrange(len(votes)) :
for v in xrange(270+votes[n]-1, votes[n]-1, -1) :
ways[v] += ways[v-votes[n]]
print sum(ways[k] for k in ways.iterkeys() if k >= 270)

Leave a comment