Which Lockers are Open?

What is the problem statement regarding 100 lockers and 100 students?

Analysis:

The problem is asking us to determine which lockers are open after all the students have passed through the building and changed the lockers. There are 100 lockers and 100 students. Initially, all lockers are closed.

Design:

To solve the problem, we can follow these major steps: 1. Create an array of 100 boolean elements to represent the lockers' state. 2. Initially, set all lockers to closed (false). 3. Iterate through each student starting from 1 to 100. 4. For each student, iterate through the lockers based on their student number and change the locker state accordingly. 5. After all students have passed through and changed the lockers, identify and print out the index of the open lockers.

My Current Code:

public class Exercise07_23 {
  public static void main(String[] args) {
    boolean[] locker = new boolean[101];
    // set all locks to false
    for (int i=1; i <= 100; i++) {
      locker[i] = false;
    }
    // first student opens all lockers
    for (int i=1; i <= 100; i++) {
      locker[i] = true;
    }
    for (int S=2; S <= 100; S++) {
      for (int k=S; k <= 100; k += S) {
        if(locker[k]==false) locker[k] = true;
        else locker[k] = false;
      }
    }
    for (int S=1; S <= 100; S++) {
      if (locker[S]) {
        System.out.println("Locker " + S + " is open");
      }
    }
  }}
[Python code provided for reference]

← Enhancing a c code to solve and display a maze Are you afraid of laptop shock during a thunderstorm check this out →