Minimum coin change algorithm - ES6 solution

Very nice math algorithm! Thx Craig Ayre for that beauty solution!

Code & explanation!

const banknotes = [5000, 1000, 500, 100, 50]
const sum = 8550

const coinChanger = (denominations, amount) =>
    // copy our array to prevent editing original
    [...denominations]
        // sort our by descending
        .sort((a, b) => b - a)
        .reduce(({ coins, remainder }, value) => ({
            coins: {
                ...coins,
                // here we count how many coints we can get, based on our current remainder
                [value]: Math.floor(remainder / value)
            },

            // recount our remainder, and go next coin
            remainder: remainder % value
        }), { remainder: amount, coins: {} }) // <-- important part, our initial value

// of remainder is our amount (our start sum)


const coins = coinChanger(banknotes, sum)

console.log(coins)

  • Slider

You may also like

  • Slider
  • Slider
2 comments

John Doe

Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non | numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Reply