Skip to content

Instantly share code, notes, and snippets.

@anthonynichols
Created January 6, 2017 03:54
Show Gist options
  • Save anthonynichols/e647bb97ec5bb0879e86d45fba52a4ef to your computer and use it in GitHub Desktop.
Save anthonynichols/e647bb97ec5bb0879e86d45fba52a4ef to your computer and use it in GitHub Desktop.
// Coins
const COINS = [25, 10, 5, 1]
const TOTAL = 18
let storedValues = new Map()
function minCoins(coins, total) {
let coinsUsed = getCoinsUsedInTotal(coins, total)
console.log(`Total Number of Coins: ${coinsUsed.length}`)
console.log(`Coins used: ${coinsUsed}`)
}
function getCoinsUsedInTotal(coins, total) {
if (!total) {
return []
}
if (storedValues.has(total)) {
return storedValues.get(total)
}
let usedCoins = []
for (let coin of coins) {
if (coin > total) {
continue
}
let remainder = total - coin
let currentCoins = getCoinsUsedInTotal(coins, remainder)
let isRemainderZero = (remainder === 0)
let isCurrentCoinsFewerThanUsedCoins = (currentCoins.length < usedCoins.length)
if (remainder >= 0) {
if (isCurrentCoinsFewerThanUsedCoins || !usedCoins.length) {
if (currentCoins.length || isRemainderZero) {
usedCoins = [coin].concat(currentCoins)
}
}
}
}
storedValues.set(total, usedCoins)
return storedValues.get(total)
}
minCoins(COINS, TOTAL)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment