2010-06-22 4 views
2

숫자 배열 frm을 무작위로 생성하려면 & 모든 숫자가 고유해야합니다. 코드 조각을 제공합니다. 친절하게 도와주세요, & plz dnt arraylist, bcoz에 대한 제안은 & blackberry api가 arraylist 또는 collection 또는 hashset을 지원하지 않으므로 친절하게도 코드 조각에만 배열을 제안 해주세요.임의로 Java에서 배열의 unqiue 번호를 생성하는 방법

Random rgen = new Random(); // Random number generator 

    //--- Initialize the array 
    for (int i=0; i<20; i++) { 
     quesNum[i] = i; 
    } 

// --- 각 요소를 무작위로

for (int i=0; i< 20; i++) { 
     int randomPosition = rgen.nextInt(20); 

     int temp = quesNum[i]; 

     quesNum[i] = quesNum[randomPosition]; 

     quesNum[randomPosition] = temp; 


    } 
+0

이 코드가 원하지 않는 일이나이 코드가 원하지 않는 것을 설명 할 수 있습니까? –

답변

4

코드를 교환하여 셔플 그대로 거의 괜찮지 만, 대신 수정 Fisher-Yates shuffle을 사용해야합니다

for (int i=0; i < 20; i++) { 
    // Partition the array into "shuffled" at the start 
    // and "unshuffled" at the end. Select a random 
    // unshuffled one, and swap it with the one at the 
    // border of shuffled/unshuffled 
    int randomPosition = i + rgen.nextInt(20 - i); 
    int temp = quesNum[i]; 
    quesNum[i] = quesNum[randomPosition]; 
    quesNum[randomPosition] = temp; 
} 

귀하의 질문에서 당신이 요구하는 것이 분명하지 않았습니다 - 당신이 올바른 라인을 따라 생각하고 있다는 확인입니까? 이 답이 도움이되지 않으면 질문을 명확히하십시오 (이상적으로 말하면 약자를 말하지 않는 것이 이상적입니다).

관련 문제