100 doors - Rosetta Code

Hey, guys. I’m stuck with 100 doors from interview prep section. I’m getting the correct results (I think) but it won’t let me pass for some reason. Guess I’m doing something wrong. Can you pls take a look?

function getFinalOpenedDoors(numDoors) {
    let doors = [];
    let ind = [];
    let iter = 2;

    for (let a = 0; a <= numDoors; a++) {
        doors.push('o' + a);
    } //all the doors are opened after first time through

    while (iter < numDoors) {
        for (let b = iter; b < doors.length; b += iter) {
            if (doors[b][0] === 'o') {
                doors[b] = doors[b].replace('o', 'c');
            } else doors[b] = doors[b].replace('c', 'o');
        }
        iter++;
    } //opening-closing loop
    doors.splice(1).forEach(function(e) {
        if (e[0] === 'o') {
            ind.push(e.substring(1))
        }
    }) //removing door 0 and getting opened doors
    return ind;
}
getFinalOpenedDoors(100);

Are you sure you are making 100 passes?

Try logging iter to console to see where you end up. Remember on the final value of iter that loop doesn’t execute - that is the value that fails the condition of the while…loop.

1 Like