Potential infinite loop detected on line 10. Tests may fail if this is not changed

Hi my loop is not infinite but the console stop executing, how to fix this?
It said
“Potential infinite loop detected on line 12. Tests may fail if this is not changed.
Potential infinite loop detected on line 11. Tests may fail if this is not changed.
Potential infinite loop detected on line 10. Tests may fail if this is not changed.
Potential infinite loop detected on line 9. Tests may fail if this is not changed.
Potential infinite loop detected on line 8. Tests may fail if this is not changed.
Potential infinite loop detected on line 7. Tests may fail if this is not changed.”

function checkCashRegister(price, cash, cid) {
  let moneyArr= cid.map(x=>x[1]);
  let total = moneyArr.map(x=>x*100).reduce((acc,ele)=>acc+ele);
  total=total/100;
  let change=cash-price;
//---------------------------------------------------------
  for (let hundred=cid[8][1];hundred>=0;hundred-=100){
    for (let twenty=cid[7][1];twenty>=0;twenty-=20){
      for (let ten=cid[6][1];ten>=0;ten-=10){
        for (let five=cid[5][1];five>=0;five-=5){
          for(let one=cid[4][1];one>=0;one--){
            for(let quarter=cid[3][1];quarter>=0;quarter-=0.25){
              for(let dime=cid[2][1];dime>=0;dime-=0.1){
                for(let nickel=cid[1][1];nickel>=0;nickel-=0.05){
                  for (let penny=cid[0][1];penny>=0;penny-=0.01){
                    let searchForChange=hundred+twenty+ten+five+one+quarter+dime+nickel+penny;
                    if(searchForChange===change){
                      return "Test Success";
                    }
                  }
                }

              }
            }
          }
        }
      }
    }
  }
//----------------------------------------------------------

}

checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]);

You have nested too many loops together. You really don’t want all of those loops nested in your solution.

1 Like

Never seen a for loop pyramid of dome before. That looks scary. :scream:

As said, you will want to rethink your approach here.

1 Like

Thanks, I found another solution which I don’t have to use loops nested in loop to search for equality

I have never seen that many loops in one place! I think your computer took one look and said
“Nope, Im not touching that with a 40 foot pole!”

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.