Search code examples
javascriptrosetta-code

Why is my code outputting only "opened" and not "closed"?


This is a 100 doors Rosseta code challenge. I have been trying to figure out why the output is all "opened". I don't understand why, since when I go through the loop, it makes sense logically.

function getFinalOpenedDoors(numDoors) {
  // Good luck!
  const DOOR_ARR = [];
  const FINALDOOR_ARR = [];
  for(let i = 1; i <= numDoors; i++){
    DOOR_ARR.push("D" + i);
    //DOOR_ARR[i - 1] = "D" + i + " is closed";
    DOOR_ARR[i - 1] = "closed";
  }

  for(let j = 1; j <= numDoors; j ++){

    for(let n = 1; n <= numDoors / j; n ++){

      if(DOOR_ARR[(n * j) - 1] = "closed"){

        DOOR_ARR[(n * j) - 1] = "opened";


      }
      else{
        DOOR_ARR[(n * j) - 1] = "closed";
      }
    }


        /*DOOR_ARR[(n * j) - 1] = "D" + DOOR_ARR[(n * j) - 1] + " is closed" ? "D" + DOOR_ARR[(n * j) - 1] + " is opened" : "D" + DOOR_ARR[(n * j) - 1] + " is closed";*/
  }

  return DOOR_ARR;
}

Solution

  • You may want to use == in your if statement:

    if(DOOR_ARR[(n * j) - 1] == "closed"){
    

    Sorry I don't have the reputation to add a comment.