100 doors -- For Loops not looping right number of times

100 doors -- For Loops not looping right number of times
0

#1

Tell us what’s happening:

For some reason, my for loops aren’t executing the number of times they should. If you look at the last loop in my code, purely for testing:

for (i = 0; i < 1000; i++) { 
    console.log("loop called")
}

It only logs loop called 22 times! What’s wrong?

Your code so far


function getFinalOpenedDoors(numDoors) {
  console.log("numDoors:" + numDoors)
  var doors = Array(numDoors)
  doors.fill(false)
  console.log("Doors: " + doors)
  var resultArray = []
  var loop = 0
  for (var i = 1; i < numDoors + 1; i++) {
    loop += 1
    console.log("loop called")
    for (var j = i; j < numDoors + 1; j = j + i) {
      console.log("+1")
      if (doors[j]) {
        doors[j] = false
      } else {
        doors[j] = true
      }
    continue
    }
  }
  console.log("loop called %s times", loop)

  for (var k = 0; k < numDoors; k++) {
    console.log("k:" + k)
    if (doors[k]) {
      resultArray.push(k+1)
    }
  }
  console.log("resultArray: " + resultArray)
  return resultArray
}
var newLoop
for (var i = 0; i++; i<1000) {
  newLoop ++
}

console.log("newLoop called %s times", newLoop)

for (i = 0; i < 1000; i++) { 
    console.log("loop called")
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/coding-interview-prep/rosetta-code/100-doors/


#2

Console.logs are expensive (in time taken to work) as far as displaying to the screen. Free Code Camp has an infinite loop protection which seems to kick in if any script takes more than 100ms to execute. After 22 iterations of console statements, it just stops executing.


#3

I’ve been using repl.it as a scratch pad to solve such things and then copying my final solution into FCC. repl is more forgiving with the infinite loop timeouts and there is a stop button that (sometimes) lets you kill a long-running script. Unlike codepen, your scripts don’t run automatically upon opening the page, you have to press run button, so if you have to close a tab to kill a script you can safely revisit it later

In repl I was able to console.log out my open / closed doors as . and X so I could watch the pattern emerge over time. Cool stuff that I couldn’t do on FCC.


#4

Okay, thanks! I removed the console.logs and tweaked some things and now it works. @QuincyLarson Maybe this would be an issue to fix?