Home > Software engineering >  Uncaught RangeError: Maximum call stack size exceeded, recursion with random numbers?
Uncaught RangeError: Maximum call stack size exceeded, recursion with random numbers?

Time:04-28

So I know max call stack error is appearing when infinite loop is in occurring, by recursion. But I'm having this weird problem. Everything in code under works fine, until I add these 2 commented lines under randomRow and randomCol. Is it possible to create infinite loop with random numbers or am I missing something?

function insertNumbers(freeRCPos, grid, fields, num) {
//base case
if (fields.length === 0) return grid;


let randomRow = Math.floor(Math.random() * maxRows);
let randomCol = Math.floor(Math.random() * maxRows);
// if (grid[randomRow][randomCol].value !== undefined)
//   return insertNumbers(freeRCPos, grid, fields, num);

let newFields = [];
//there are in total 9 fields so it has to go through all of them  
for (let field of fields) {
//check if its already in field
if (field.includes(JSON.stringify([randomRow, randomCol]))) {
  let res = freeRCPos.map((element: any) =>
    element.map((pos: any) =>
      pos === JSON.stringify([randomRow, randomCol]) ? true : false
    )
  );
  if (
    res.filter((el: any) => (el.includes(true) ? true : false)).length > 0
  ) {
    grid[randomRow][randomCol].value = num;
    newFields= fields.filter(
      (_: any, fieldId: number) => fields.indexOf(field) !== fieldId
    );
    //return with modified fields and others to be able to complete base case
    return insertNumbers(
      freeRCPos.map((field: any) =>
        field.map((pos: string) =>
          pos?.startsWith("["   randomRow) || pos?.endsWith(randomCol   "]")
            ? null
            : pos
        )
      ),
      grid,
      newFields,
      num,
    );
  //else return same
  } else {
    return insertNumbers(freeRCPos, grid, fields, num);
  }
//else return same
} else {
  return insertNumbers(freeRCPos, grid, fields, num);
}
}
return grid;
}

I've maybe put a lot of unnecessary code here so if I need to shorten it, just ask. Appreciate the help.

CodePudding user response:

If the random numbers are the existing indexes in grid (= if grid[randomRow][randomCol].value !== undefined is true), it will never pass the commented part and it will keep calling itself with the same values. You need to update something before calling the function recursively and get closer to the base case which is fields.length === 0.

  • Related