Skip to content

Instantly share code, notes, and snippets.

@sundeep-peswani
Created July 15, 2013 08:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sundeep-peswani/5998235 to your computer and use it in GitHub Desktop.
Save sundeep-peswani/5998235 to your computer and use it in GitHub Desktop.
Solution to the puzzle of 50 coins to make a dollar From: http://richardwiseman.wordpress.com/2013/07/15/answer-to-the-friday-puzzle-214/
#!/usr/bin/env node
var AMOUNT = 1,
COINS = [0.01, 0.05, 0.1, 0.25, 0.5],
TOTAL_COINS = 50;
var solve = function(amount_needed, coins_remaining, coin_type, cb) {
if (coin_type < 0) return;
var coin = COINS[coin_type],
max_usable_coins = Math.min(coins_remaining, Math.floor(amount_needed / coin)),
solution = {};
//console.info('Need: $%d, Using $%d, With: %d coins left, Max: %d', amount_needed, coin, coins_remaining, max_usable_coins);
for (var ii = max_usable_coins; ii >= 0; ii--) {
var amount_left = Math.floor(amount_needed * 100 - coin * 100 * ii) / 100,
coins_left = coins_remaining - ii;
if (amount_left < 0) continue;
if (amount_left == 0 && coins_left == 0) {
solution[coin.toFixed(2)] = ii;
cb(null, solution);
}
// inception
solve(amount_left, coins_remaining - ii, coin_type - 1, function (err, solution) {
if (err) return cb(err);
solution[coin.toFixed(2)] = ii;
cb(null, solution);
});
}
};
var fmtSolution = function(solution) {
var stringified = [];
for (var coin in solution) {
var num = solution[coin];
if (num == 0) continue;
switch (coin) {
case '0.01':
stringified.push(num + ' penn' + (num > 1 ? 'ies' : 'y'));
break;
case '0.05':
stringified.push(num + ' nickel' + (num > 1 ? 's' : ''));
break;
case '0.10':
stringified.push(num + ' dime' + (num > 1 ? 's' : ''));
break;
case '0.25':
stringified.push(num + ' quarter' + (num > 1 ? 's' : ''));
break;
case '0.5':
stringified.push(num + ' half-dollar' + (num > 1 ? 's' : ''));
break;
}
}
return stringified.join(', ');
};
solve(AMOUNT, TOTAL_COINS, COINS.length - 1, function _onSolutionFound(err, solution) {
if (err) return;
console.error('Solution: ', fmtSolution(solution));
});
@sundeep-peswani
Copy link
Author

Two solutions found:

Solution:  45 pennies, 2 nickels, 2 dimes, 1 quarter
Solution:  40 pennies, 8 nickels, 2 dimes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment