안드로이드 개발 질문/답변
(글 수 45,052)
안녕하세요?
안드로이드 초보로 열심히 하고있는 학생입니다.
현제 열심히 공부하고있다가 너무 막혀서 질문 하러 왔습니당 ㅠ
class xx extends Activity{
Random rand = new Random();
int index1=0,index1=0,index3=0;
...
...
public void onCreate(Bundle savedInstanceState) {
index1 = rand.nextInt(3);
index2 = rand.nextInt(3);
index3 = rand.nextInt(3);
while(index1 != index2 && index1 != index3 && index2 != index3){
index1 = rand.nextInt(3);
index2 = rand.nextInt(3);
index3 = rand.nextInt(3);
}
....
현제 구하려고 하는게 배열에 3개자 정보가 들어가있는데
index 값을 각각 index1 , index , index3 으로
난수는 0 ,1 ,2 세가지만 두려고 합니다.
현제 이렇게 구현 해봤는데 난수가 중복이 됩니다.
세개다 틀리게 나올때도 있지만 반드시 중복이 되면 안되기 때문에
질문을 드립니당
어떻게 하면 될까요?
많은 조언 부탁드립니다! 꾸벅 (--) (__)




만들어보긴 했는데... 원하는 것인지는 잘 모르겠네요...
public static void main(String[] args) {
int[] counts = new int[]{0,0,0,0,0,0}; //경우의수를 각각 카운트(검산용)(arr 배열이 3개일때만 가능)
Random rand = new Random(System.currentTimeMillis());
for (int loop = 0; loop < 100000; loop++) {
int[] arr = new int[]{0,1,2};//new int[]{0,1,2,3,4,5,6,7,8,9}; //arr.length가 3개일때 보다는 100개쯤 될때 필요한 알고리즘임
for (int i=0; i<arr.length*2; i++) { //2배수만큼 돌려야 골고루 잘 섞임
int idx1 = rand.nextInt(arr.length);
int idx2 = rand.nextInt(arr.length);
if (idx1 == idx2) continue;
int temp = arr[idx1];
arr[idx1] = arr[idx2];
arr[idx2] = temp;
}
// for (int i=0; i<arr.length; i++) {
// System.out.println(arr[i]);
// }
//경우의수 카운트(arr 배열이 3개일때만 가능)
if (arr[0] == 0 && arr[1] == 1 && arr[2] == 2) counts[0]++;
if (arr[0] == 0 && arr[1] == 2 && arr[2] == 1) counts[1]++;
if (arr[0] == 1 && arr[1] == 0 && arr[2] == 2) counts[2]++;
if (arr[0] == 1 && arr[1] == 2 && arr[2] == 0) counts[3]++;
if (arr[0] == 2 && arr[1] == 0 && arr[2] == 1) counts[4]++;
if (arr[0] == 2 && arr[1] == 1 && arr[2] == 0) counts[5]++;
}
for (int i=0; i<counts.length; i++) {
System.out.println(counts[i]);
}
// 출력 결과
// 16725
// 16484
// 16750
// 16803
// 16461
// 16777
}