Skip to content

Instantly share code, notes, and snippets.

@msamgan
Created June 8, 2022 06:20
Show Gist options
  • Save msamgan/018e6f9a41f1b7630791711584efe5dc to your computer and use it in GitHub Desktop.
Save msamgan/018e6f9a41f1b7630791711584efe5dc to your computer and use it in GitHub Desktop.
write a program that will be used in a vending machine to return change
/**
* Problem Statement:
*
* A vending machine has the following denominations: 1c, 5c, 10c, 25c, 50c, and $1.
* Your task is to write a program that will be used in a vending machine to return change.
* Assume that the vending machine will always want to return the least number of coins or notes.
* Devise a function getChange (M, P)
* where M is how much money was inserted into the machine and P the price of the item selected,
* that returns an array of integers representing the number of each denomination to return.
*
* Example:
* getChange (5, 0.99) // should return [1,0,0,0,0,4]
* getChange (3.14, 1.99) // should return [0,1,1,0,0,1]
* getChange (3, 0.01) // should return [4,0,2,1,1,2]
* getChange(4, 3.14) // should return [1,0,1,1,1,0]
* getChange (0.45, 0.34) // should return [1,0,1,0,0,0]
*/
/**
* Calculates the change given the amount of money and the price of the item.
* @param {number} m - the amount of money given
* @param {number} p - the price of the item
* @returns {number[]} - the change given in the form of an array of numbers
*
* @author: msamgan
* @date: 8th June, 2022
* @version: 1.0
*/
const getChange = async (m, p) => {
console.log(`m: ${m}, p: ${p}`);
if (p > m) {
console.log("ERROR: Not enough money");
return;
}
let denominations = [1, 5, 10, 25, 50, 100];
let change = [0, 0, 0, 0, 0, 0];
let changeAmount = Number(m - p).toFixed(2);
let changeAmountFloor = Math.floor(changeAmount);
let decimalPart = Number(changeAmount.toString().split(".")[1]);
for (let i = 1; i <= denominations.length; i++) {
let changeIndex = denominations.length - i;
if (i === 1) {
change[changeIndex] = changeAmountFloor;
continue;
}
let dividend = decimalPart / denominations[changeIndex];
if (dividend <= 0) {
continue;
}
change[changeIndex] = Math.floor(dividend);
decimalPart = Number(
(decimalPart - Math.floor(dividend) * denominations[changeIndex]).toFixed(
2
)
);
}
return change;
};
// sample inputs
// 5, 0.99
// 3.14, 1.99
// 3, 0.01
// 4, 3.14
// 0.45, 0.34
getChange(3.14, 1.99).then((response) => {
console.log(response);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment