0

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))
Qaqli
  • 179
  • 7

0 Answers0