2 years ago

#67794

test-img

Julian Brooks

Infinite Loop; Condition is met

I'm having an issue with a for loop that won't end even though one of its conditions is met. The condition in question is the dir + i * move < 0. I can start the loop at 0 and it will begin to decrement itself, immediately starting at -1 on the first iteration. Why wouldn't it immediately stop?

I put a safety inside the loop (if (dir + i * move < 0) { break; }) to break it if that same condition is met and it works, but I didn't think I would have to do that. Even if the loop has to cycle once before it checks its conditions shouldn't it stop looping at that point?

Any help is greatly appreciated!

Here's the JS:

function focusNearest(cell, xDist, yDist) {

let answers = Object.keys(newPuzzle.answerKey);
let orderedRows = activeRows.sort(function(a, b) { return a - b; })
let orderedCols = activeCols.sort();

let id = cell.id;
let split = id.match(/[\d\.]+|\D+/g);
let col = split[0];
let row = parseInt(split[1]);
let x = orderedRows.indexOf(row);
let y = orderedCols.indexOf(col);

let across = Math.abs(xDist) > Math.abs(yDist);
let axis = across ? orderedCols : orderedRows;
let dir = across ? y : x;
let move = across ? xDist : yDist;

let destX;
let destY;
let destRow;
let destCol;

let destination;

let currPos = activeGroup.indexOf(id);

for (let i = 1; dir + i * move < axis.length || dir + i * move < 0; i++) {

    // TEST
    if (dir + i * move < 0) { break; } // TODO: REMOVE

    let jumpX = xDist * i;
    let jumpY = yDist * i;

    destX = x + jumpY;
    destY = y + jumpX;
    destRow = activeRows[destX];
    destCol = activeCols[destY];
    candidate = destCol + destRow;

    if (answers.includes(candidate)) {
        destination = candidate;
        break;
    }

}

focusCell(destination, selectDir(destination)[0]);

}

javascript

for-loop

infinite-loop

0 Answers

Your Answer

Accepted video resources