Last active
February 17, 2023 05:34
-
-
Save joaosouz4dev/d9bcce6f45f1af0aa3b337db847ec09d to your computer and use it in GitHub Desktop.
Javascript Cash Withdrawal like Cash Machine
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
// function in javascript that performs a withdrawal based on the balance and an array of banknotes available, for example, I need to withdraw 5 reais, and there are notes of 5 notes of 10, 4 notes of 20, 3 of 50, 5 of 100, so it would not have value of 5 reais, and if I withdraw 550 I discount it on the bills and I always do it in the best way possible | |
function cashWithdrawal(value, availableNotes) { | |
let notes = []; | |
let availableNotesOriginal = structuredClone(availableNotes); | |
// array com os valores de todas as notas disponíveis | |
const allNotesValues = Object.keys(availableNotes).map((note) => Number(note)).sort((a, b) => b - a); | |
for (const subsetNotes of subsets(allNotesValues, 0, 2)) { | |
let remainingValue = value; | |
for (const noteValue of subsetNotes) { | |
// quantas notas desse valor eu preciso? | |
const need = Math.min(Math.floor(remainingValue / noteValue), availableNotes[noteValue]); | |
for (let i = 0; i < need; i++) { // adiciona as notas | |
notes.push(noteValue); | |
} | |
// subtrai a quantidade e atualiza o valor restante | |
availableNotes[noteValue] -= need; | |
remainingValue -= noteValue * need; | |
} | |
if (remainingValue == 0) { // se o valor zerou, é porque deu certo | |
const availableNotesSum = Object.entries(availableNotes).reduce((sum, [note, quantity]) => sum + Number(note) * quantity, 0); | |
return { | |
notes, | |
availableNotes, | |
availableNotesSum | |
}; | |
} else { | |
// se não deu certo, zera o array de notas e volta para as notas disponíveis original | |
notes = []; | |
availableNotes = JSON.parse(JSON.stringify(availableNotesOriginal)); | |
} | |
// se o valor não zerou, é porque não foi possível, então tenta com a próxima combinação de notas | |
} | |
return null; // se tentou todas as combinações e chegou aqui, é porque não é possível | |
} | |
// Example of use: | |
const availableNotes = {10: 4, 20: 4, 50: 3, 100: 5}; | |
const value = 580; | |
console.log('availableNotesSum', Object.entries(availableNotes).reduce((sum, [note, quantity]) => sum + Number(note) * quantity, 0)) | |
const result = cashWithdrawal(value, availableNotes); | |
console.log(result); | |
// { | |
// notes: [100, 100, 100, 100, 100, 50, 50, 50, 20, 20, 20, 20, 10, 10, 10, 10], | |
// remainingValue: 0, | |
// availableNotes: {10: 0, 20: 0, 50: 0, 100: 1}, | |
// availableNotesSum: 100, | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment