Created
January 6, 2017 03:54
-
-
Save anthonynichols/e647bb97ec5bb0879e86d45fba52a4ef to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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