This Gist was automatically created by Carbide, a free online programming environment.
Created
November 26, 2016 23:36
-
-
Save matt-fff/68e531cbe72369612af577ddcc3d4baa to your computer and use it in GitHub Desktop.
untitled
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
var cashMap = { | |
PENNY: 0.01, | |
NICKEL: 0.05, | |
DIME: 0.10, | |
QUARTER: 0.25, | |
ONE: 1, | |
FIVE: 5, | |
TEN: 10, | |
TWENTY: 20, | |
FIFTY: 50, | |
'ONE HUNDRED': 100 | |
}; | |
function getRegister(cid) { | |
var total = 0; | |
var reg = {}; | |
cid.forEach(function(cash) { | |
reg[cash[0]] = cash[1]; | |
total += cash[1]; | |
}); | |
reg.total = total; | |
return reg; | |
} | |
function getNextBill(reg, diff) { | |
var highestBill; | |
Object.keys(cashMap).forEach(function(key) { | |
// Check if this value goes over the change requirement | |
if (diff >= cashMap[key]) { | |
// Check if this denomination is available | |
if (reg[key] > 0) { | |
// Check if the change value is higher than before | |
if (highestBill === undefined || highestBill[1] < cashMap[key]) { | |
highestBill = [key, cashMap[key]]; | |
} | |
} | |
} | |
}); | |
// If we found it, work out how many we can take | |
if (highestBill !== undefined) { | |
var key = highestBill[0]; | |
var val = highestBill[1]; | |
var regBills = Math.floor(reg[key] / cashMap[key]); | |
var useableBills = Math.floor(diff / cashMap[key]); | |
var multiplier = Math.min(regBills, useableBills); | |
var multVal = val * multiplier; | |
highestBill[1] = multVal; | |
reg[highestBill[0]] -= multVal; | |
} | |
return highestBill; | |
} | |
function checkCashRegister(price, cash, cid) { | |
var diff = cash - price; | |
var reg = getRegister(cid); | |
var change = []; | |
while(diff > 0) { | |
var nextVal = getNextBill(reg, diff); | |
if (nextVal === undefined) | |
return 'Insufficient Funds'; | |
diff -= nextVal[1]; | |
change.push(nextVal); | |
} | |
if (reg.total === 0) | |
return 'Closed'; | |
// Here is your change, ma'am. | |
return change; | |
} | |
// Example cash-in-drawer array: | |
// [["PENNY", 1.01], | |
// ["NICKEL", 2.05], | |
// ["DIME", 3.10], | |
// ["QUARTER", 4.25], | |
// ["ONE", 90.00], | |
// ["FIVE", 55.00], | |
// ["TEN", 20.00], | |
// ["TWENTY", 60.00], | |
// ["ONE HUNDRED", 100.00]] | |
checkCashRegister(3.26, 100.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment