배열에서 요소를 무작위로 선택하는 방법


답변:


182
public static int getRandom(int[] array) {
    int rnd = new Random().nextInt(array.length);
    return array[rnd];
}

2
네,하지만 그게 generator예 라고 말씀 java.util.Random
하셔야합니다

25
Random()함수를 실행할 때마다 생성하지 않습니다 . 랜덤 생성기는 히스토리를 가지고 있어야합니다. 그렇지 않은 경우 매우 예측 가능합니다. 이 경우에는 전혀 문제가되지 않지만 array[(int)(System.currentTimeMillis() % array.length)]제안 된 솔루션만큼 좋은 점을 언급해야합니다 .
alf

4
@alf, 제안 된 솔루션만큼 좋은 것은 아닙니다. new Random()이전에 만든 것과 다른 시드를 가진 인스턴스를 만들려고합니다 Random. 짧은 시간에 함수를 두 번 호출하면 접근 방식이 끔찍하게 중단됩니다.
aioobe 2011

1
@alf 일부 시스템은 일부 옵션의 경우 배제 할 수있는 투 - 밀리 초 정확한 시계가없는gcd(array.length,clockAccuracy)!=1
래칫 괴물

3
이 답변에 반대한다는 알림을 받았습니다. 실수로 클릭 한 것 같습니다. 안타깝게도 인터페이스는 취소 할 수 없습니다 (답을 편집하지 않으면 투표를 변경할 수 없다고 표시됩니다 ...). 그래서 Chris Dennett에게 사과드립니다.
Peter Hanley

13

임의 생성기를 사용하여 임의 인덱스를 생성하고 해당 인덱스의 요소를 반환 할 수 있습니다.

//initialization
Random generator = new Random();
int randomIndex = generator.nextInt(myArray.length);
return myArray[randomIndex];

9

임의의 요소를 여러 번 가져 오려면 난수 생성기가 한 번만 초기화되도록해야합니다.

import java.util.Random;

public class RandArray {
    private int[] items = new int[]{1,2,3};

    private Random rand = new Random();

    public int getRandArrayElement(){
        return items[rand.nextInt(items.length)];
    }
}

예측 불가능해야하는 임의의 배열 요소를 선택 하는 경우 Random이 아닌 java.security.SecureRandom 을 사용해야합니다 . 이렇게하면 누군가가 마지막 몇 가지 선택을 안다면 다음 항목을 추측하는 데 이점이 없습니다.

제네릭을 사용하여 Object 배열에서 임의의 숫자를 선택하려는 경우 그렇게하는 방법을 정의 할 수 있습니다 (Source Avinash R in Random element from string array ) :

import java.util.Random;

public class RandArray {
    private static Random rand = new Random();

    private static <T> T randomFrom(T... items) { 
         return items[rand.nextInt(items.length)]; 
    }
}

3

사용 java.util.Random하여 0과 배열 길이 사이의 난수를 생성 한 random_number다음 난수를 사용하여 정수를 가져옵니다.array[random_number]


3

Random 클래스를 사용하십시오 .

int getRandomNumber(int[] arr)
{
  return arr[(new Random()).nextInt(arr.length)];
}

2

당신은 또한 사용할 수 있습니다

public static int getRandom(int[] array) {
    int rnd = (int)(Math.random()*array.length);
    return array[rnd];
}

Math.random()(포함)에서 (배타) double사이를 반환합니다.0.01.0

이것을 곱하면 array.length당신에게주는 double사이에 0.0(포함) 및 array.length(독점)

캐스트 int는 내림하여 0(포함)과 array.length-1(포함) 사이의 정수를 제공합니다.


Math.random ()은 int가 아닌 double을 반환합니다. 가능하다면 0과 1의 두 가지 가능한 값만 있었을 것입니다.
Akshay R.

1

Java 8이 있으므로 다른 솔루션은 Stream API를 사용하는 것입니다.

new Random().ints(1, 500).limit(500).forEach(p -> System.out.println(list[p]));

어디는 1(포함) 생성 가장 낮은 INT이며, 500가장 높은 (전용)입니다. limit스트림의 길이가 500임을 의미합니다.

 int[] list = new int[] {1,2,3,4,5,6};
 new Random().ints(0, list.length).limit(10).forEach(p -> System.out.println(list[p])); 

무작위는 java.util패키지 에서 가져온 것 입니다.



0

Java는 java.util 패키지에 Random 클래스가 있습니다. 이를 사용하여 다음을 수행 할 수 있습니다.

Random rnd = new Random();
int randomNumberFromArray = array[rnd.nextInt(3)];

도움이 되었기를 바랍니다!


0
package workouts;

import java.util.Random;

/**
 *
 * @author Muthu
 */
public class RandomGenerator {
    public static void main(String[] args) {
     for(int i=0;i<5;i++){
         rndFunc();
     } 
    }
     public static void rndFunc(){
           int[]a= new int[]{1,2,3};
           Random rnd= new Random();
           System.out.println(a[rnd.nextInt(a.length)]);
       }
}

0

이 방법을 시도해 볼 수도 있습니다 ..

public static <E> E[] pickRandom_(int n,E ...item) {
        List<E> copy = Arrays.asList(item);
        Collections.shuffle(copy);
        if (copy.size() > n) {
            return (E[]) copy.subList(0, n).toArray();
        } else {
            return (E[]) copy.toArray();
        }

    }

그래서 당신은 O(nlogn)시간 복잡성 으로 목록을 섞고, OP가 요구 한 문제는 O(1)시간 복잡성과 O(1)메모리 로 해결할 수 있음에도 불구하고 초기 배열보다 총 3 배 많은 메모리를 사용하여 두 번 복사 합니다 ...?
Jaroslaw Pawlak

네, 맞습니다. 일정한 시간과 공간의 복잡성으로하는 것이 더 낫습니다.
Ravi Sapariya

0
package io.github.baijifeilong.tmp;

import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Stream;

/**
 * Created by BaiJiFeiLong@gmail.com at 2019/1/3 下午7:34
 */
public class Bar {
    public static void main(String[] args) {
        Stream.generate(() -> null).limit(10).forEach($ -> {
            System.out.println(new String[]{"hello", "world"}[ThreadLocalRandom.current().nextInt(2)]);
        });
    }
}
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.