답변:
public static int getRandom(int[] array) {
int rnd = new Random().nextInt(array.length);
return array[rnd];
}
generator예 라고 말씀 java.util.Random
Random()함수를 실행할 때마다 생성하지 않습니다 . 랜덤 생성기는 히스토리를 가지고 있어야합니다. 그렇지 않은 경우 매우 예측 가능합니다. 이 경우에는 전혀 문제가되지 않지만 array[(int)(System.currentTimeMillis() % array.length)]제안 된 솔루션만큼 좋은 점을 언급해야합니다 .
new Random()이전에 만든 것과 다른 시드를 가진 인스턴스를 만들려고합니다 Random. 짧은 시간에 함수를 두 번 호출하면 접근 방식이 끔찍하게 중단됩니다.
gcd(array.length,clockAccuracy)!=1
임의의 요소를 여러 번 가져 오려면 난수 생성기가 한 번만 초기화되도록해야합니다.
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)];
}
}
당신은 또한 사용할 수 있습니다
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(포함) 사이의 정수를 제공합니다.
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패키지 에서 가져온 것 입니다.
이 질문을보세요 :
Java의 특정 범위 내에서 임의의 정수를 생성하는 방법은 무엇입니까?
0에서 정수 길이-1까지 임의의 숫자를 생성하고 싶을 것입니다. 그런 다음 배열에서 int를 가져옵니다.
myArray[myRandomNumber];
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)]);
}
}
이 방법을 시도해 볼 수도 있습니다 ..
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 배 많은 메모리를 사용하여 두 번 복사 합니다 ...?
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)]);
});
}
}