Skip to content

Instantly share code, notes, and snippets.

@mathiasverraes
Created October 2, 2013 06:49
Show Gist options
  • Save mathiasverraes/6789907 to your computer and use it in GitHub Desktop.
Save mathiasverraes/6789907 to your computer and use it in GitHub Desktop.
@MikeBild posted this on twitter. As an exercise, I made the same thing in an FP style, using recursion instead of mutable state. It's slightly longer :-) Because there's no native pattern matching, I have a calc/2 (public) and a calcX/3 (private) function. https://twitter.com/mikebild/status/385276260089225216
'use strict';
var assert = require('assert');
var _ = require('lodash');
var calcX = function (acc, coinSizes, totalAmount) {
if (coinSizes.length == 0) return acc;
var currentCoinSize = _.head(coinSizes);
var restAmount = totalAmount % currentCoinSize;
var newAcc = acc.concat([
{
coinSize: currentCoinSize,
amountOfCoins: Math.floor(totalAmount / currentCoinSize),
rest: restAmount
}
]
);
return calcX(newAcc, _.tail(coinSizes), restAmount);
};
var calc = _.partial(calcX, []);
var totalAmount = 99;
var coinSizes = [1, 2, 5, 10, 20, 50, 100].reverse();
var result = calc(coinSizes, totalAmount);
console.log(result);
var expected = [
{ coinSize: 100, amountOfCoins: 0, rest: 99 },
{ coinSize: 50, amountOfCoins: 1, rest: 49 },
{ coinSize: 20, amountOfCoins: 2, rest: 9 },
{ coinSize: 10, amountOfCoins: 0, rest: 9 },
{ coinSize: 5, amountOfCoins: 1, rest: 4 },
{ coinSize: 2, amountOfCoins: 2, rest: 0 },
{ coinSize: 1, amountOfCoins: 0, rest: 0 }
];
assert.deepEqual(result, expected);
var a=99;[1,2,5,10,20,50,100].reverse().map(function(n){return{C:n,N: Math.floor(a/n),R:(a%=n)};});
@MikeBild
Copy link

MikeBild commented Oct 3, 2013

next one without shared state ;-)

[1,2,5,10,20,50,100]
.reverse()
.reduce(function(acc, n){
    return {
        amount: acc.amount%n,
        results: acc.results.concat({Coin:n, N: Math.floor(acc.amount/n)})
    }
}, {amount:99, results:[]});

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