Question

I am trying to write an algorithm for this: There are 100 students and 100 lockers. The first student starts at the first locker and opens every one. The next student, student two, starts at the second locker and closes every second lockers if it's open, and vice versa. The third students starts at the third locker, and for every third locker, repeats the process. I wrote something I believe should work but my array is going out of bounds and I don't see how:

public static void main(String[] args) 
{
    int startingStudents = 1;
    int lockersToCheck = 1;
    int lockersPosition = 1;
    boolean[] lockers = new boolean[101];

    //Cycles through 100 students
    for(int students = startingStudents; startingStudents <= 100; students++)
    {
        //What each student does
        while(lockersToCheck <= 100)
        {
                            //If its closed, open
            if(lockers[lockersToCheck] == false)
            {
                lockers[lockersToCheck] = true;
            }
                            //If its open, close
            else
            {
                lockers[lockersToCheck] = false;
            }

                            //Which locker they should be at
            lockersToCheck += lockersPosition;
        }


        //Zero out to start at the right locker
        lockersToCheck = 0;
                    //Where the next student starts
        lockersPosition += students;
                    //Make sure the next student starts there
        lockersToCheck = lockersPosition;

    }

    for(int n = 1; n <= 100; n++)
    {
        System.out.print(lockers[n] + " " + n);
    }

}

Thanks for any help!

Was it helpful?

Solution

for(int students = startingStudents; startingStudents <= 100; students++)

should be

for(int students = startingStudents; students<= 100; students++)

OTHER TIPS

It's your loop-termination

for(int students = startingStudents; startingStudents <= 100; students++)

Should be

for(int students = 1; students <= 100; students++)

Therefore, I guess you are not getting an ArrayIndexOutOfBoundsException, but a Heap-Space-Exception.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top