Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

62
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda