Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

61
Vistas
Loop jumps one element

I'm writing a function that breaks down change into denominations and returns the updated register after change has been given. So far it's working but only if the register has enough money in the respective denominations. If the change is [ 10, 4, 0.5, 0.05 ] as in this case and there are no 10 dollar bills in the register for example, the loop should move on to 5 dollar bills and check if change can be given from those and so on. But what it does instead is it jumps right to 1 dollar bills. What am I missing here? As for indexes, those are pre-calculated in my greater function, so 10 starts going through the loop at index 2 since all denominations before that are greater than 10, 4 starts looping at index 4 since that is the index of 1 dollar bills in the cash register, and so on.

let change = [ 10, 4, 0.5, 0.05 ]
let denomin = [ 100, 20, 10, 5, 1, 0.25, 0.1, 0.05, 0.01 ]
let register = [ 100, 60, 0, 55, 90, 4.25, 3.1, 2.05, 1.01 ]
let idx = [ 2, 4, 5, 7 ]

function test(ch, reg, idx) {
    for (let x of ch) {
        for (let i = idx[ch.indexOf(x)]; i < reg.length; i++) {
            if (reg[i] - x >= 0) {
                reg[i] -= x
                break;
            } else if (reg[i] - x < 0) {
                i++
            }
        }
    }
    return reg = reg.map(a => Number(a.toFixed(2)))
}

console.log(test(change, register, idx))

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda