Tell us what’s happening:
So I was able to hack this algorithm together to pass the challenge but I’m a bit confused about the initial for-loop. I originally had let i = 0 instead of let i = 1 and just ended up changing the value of i as a guess and it turned out to be the right answer.
I’m confused because when I initialize the array of doors like this:
for (let i = 1 ; i < numDoors; i++){
arr[i] = 'closed'
}
I end up getting an array with a length of 100, but index 0 is ‘empty’ since i starts at 1. So I ended up with doors starting at index 1 and stopping at index 99 which means there are only 99 doors?
How did I end up passing the challenge with this ?
My original answer had the intial for loop like this (with the array indexed from 0-99 which would equal 100 doors):
for (let i = 0 ; i < numDoors; i++){
arr[i] = 'closed'
}
Your code so far
function getFinalOpenedDoors (numDoors) {
let arr = []
for (let i = 1 ; i < numDoors; i++){
arr[i] = 'closed'
}
function toggle(x){
if (x === 'closed'){
x = 'open'
} else {
x = 'closed'
}
return x
}
let counter = 1
while (counter !== 100){
for (let i = 0 ; i <= 100; i+=counter){
arr[i] = toggle(arr[i])
}
counter++
}
let final = []
for (let i = 0 ; i < arr.length; i++){
if (arr[i] === 'open'){
final.push(i)
}
}
return final
}
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.
Link to the challenge:
https://learn.freecodecamp.org/coding-interview-prep/rosetta-code/100-doors