我正在寻找从整数数组中随机选择数字的解决方案。
例如,我有一个数组new int[]{1,2,3}
,如何随机选择一个数字?
我正在寻找从整数数组中随机选择数字的解决方案。
例如,我有一个数组new int[]{1,2,3}
,如何随机选择一个数字?
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)
的时间复杂度洗牌一个列表,将其复制两次,使用的内存总量是初始数组的3倍,即使OP提出的问题可以用O(1)
的时间复杂度和O(1)
的内存解决...? - Jaroslaw Pawlakpackage 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)]);
});
}
}