2012-09-29 5 views
0

나는 이것을위한 알고리즘을 쓰려고합니다 : 100 명의 학생과 100 개의 사물함이 있습니다. 첫 번째 학생은 첫 번째 보관함에서 시작하여 모든 보관함을 엽니 다. 다음 학생 인 학생 2는 두 번째 보관함에서 시작하고 두 번째 보관함이 열려 있으면 닫습니다. 그 반대의 경우도 마찬가지입니다. 세 번째 학생은 세 번째 로커에서 시작하고 세 번째 로커마다 한 번씩 과정을 반복합니다. 내가 일을한다고 생각 뭔가를 썼다하지만 내 배열 범위를 벗어 가고 나는 보이지 않는 방법 :내 배열은 어디에서 벗어 납니까?

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); 
    } 

} 

어떤 도움 주셔서 감사합니다! 위한

답변

2

는 (; startingStudents < = 100; 학생 = startingStudents int로 학생 ++)

+0

Wooooow .... 그게 내가 수면을 방해하는 것입니다. 고마워 션. –

+0

그건 그렇고 ... 루프의 끝에있는 lockerPosition은 + + 학생이 아닌 + ++이어야합니다. 혹시 궁금한 점이 있으시면 :-) –

0

이어야 (; 학생 < = 100 명 ++ 학생 = startingStudents를 INT) 루프 종단입니다.

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

따라서

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

될 경우, 나는 당신이는 ArrayIndexOutOfBoundsException를받지 못하고있다 생각하지만, 힙 - 공간 예외입니다.

+0

예 Andy you correct. 나는 내부 논리에 초점을 맞추어서 for 루프 조건을 지나치게 감추었다. –

관련 문제