Last active
June 12, 2021 17:14
-
-
Save Said210/4ca7249b80b4571a3ba967e5535ec665 to your computer and use it in GitHub Desktop.
Implementación de un algoritmo voraz / avido en JS para el problema de dar cambio.
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
// DATASET EXAMPLE. | |
let coins_sorted = [ | |
{value: 500, amount: 4}, | |
{value: 200, amount: 0}, | |
{value: 100, amount: 1}, | |
{value: 50, amount: 0}, | |
{value: 20, amount: 5}, | |
{value: 10, amount: 3}, | |
{value: 5, amount: 2}, | |
{value: 2, amount: 5}, | |
{value: 1, amount: 5}, | |
{value: 0.5, amount: 5}, | |
{value: 0.25, amount: 5}, | |
{value: 0.10, amount: 10}]; | |
function cambio(cantidad_p = 0, disponible_p = []){ | |
// ORDENAMOS LA ENTRADA. | |
let disponible = disponible_p.sort((a,b) => (a.value > b.value) ? -1 : ((a.value == b.value) ? 0 : 1)); | |
let cantidad = cantidad_p; | |
let finished = false; | |
let result = []; | |
let i = 0; | |
let overflow = 0; | |
// MIENTRAS LA CANTIDAD SEA MAYOR A 0 Y NO HAYA TERMINADO | |
while(cantidad > 0 && !finished && i < disponible.length && overflow < 199){ | |
// SI HAY DISPONIBLES AUN y EL DISPONIBLE ES MENOR A LA CANTIDAD. | |
if (disponible[i].amount > 0 && disponible[i].value <= cantidad){ | |
cantidad = cantidad - disponible[i].value; | |
disponible[i].amount--; | |
if (result[i] === undefined) { | |
result[i] = {value: disponible[i].value, amount: 1}; | |
}else{ | |
result[i].amount++; | |
} | |
} | |
// Si se dio todo el cambio | |
if (cantidad == 0) {finished = true;} | |
// Si no hay mas denominaciones. | |
if (i == disponible.length-1 && !finished) { console.log("No hay cambio suficiente."); break;}; | |
// Si ya no se puede dar mas cambio de esta denominación | |
if (disponible[i].amount == 0 || disponible[i].value > cantidad ) {i++;} | |
if (overflow == 198) {console.error("Function overflow")} | |
overflow ++; | |
} | |
return result.filter((e) => e); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment