如何从数组中随机选择一个元素

145

我正在寻找从整数数组中随机选择数字的解决方案。

例如,我有一个数组new int[]{1,2,3},如何随机选择一个数字?


请参考此链接:http://download.oracle.com/javase/1.5.0/docs/api/java/util/Random.html#nextInt%28int%29。 - Mithun Sasidharan
13个回答

-1
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)]);
       }
}

-1

你也可以尝试这种方法。

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 Pawlak
是的,你说得对,最好使用恒定的时间和空间复杂度来完成。 - Ravi Sapariya

-1
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)]);
        });
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接