Created
December 6, 2014 09:18
-
-
Save rjchatfield/40871b40067dc20ad039 to your computer and use it in GitHub Desktop.
FP solve the Change Problem
This file contains 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
# | |
# FP solve the Change Problem | |
# eg. myChange = calcChange(cost, myPayment) | |
# | |
# Used in fold() to build change object | |
# Should be nested in calcChange, but is lifted for cleanliness | |
coinAccStructure = (acc, coin) -> | |
change = acc["payment"] | |
acc[coin] = change % coin | |
acc["payment"] = change / coin | |
acc | |
# Curried calculator | |
calcChange = (coins) -> (cost, payment) -> | |
coins.fold(coinAccStructure, {"payment": payment}).omit "payments" | |
# Initalisated calculator for Australian coins | |
auCoins = [2, 1, .5, .2, .1, .05] | |
calcAuChange = calcChange(auCoins) | |
# Use | |
cost = 5.20 | |
payment = 10.00 | |
change = calcAuChange(cost, payment) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Had a crack at it this morning, take a look at my fork.