简体   繁体   English

如何在Java中获得不同的随机值?

[英]How to get distinct random values in java?

Here is my problem: I have an array of integers, I would recover 20% of the array elements in a random manner. 这是我的问题:我有一个整数数组,我将以随机方式恢复20%的数组元素。 Is there a function in java to have more than a random value? Java中是否有一个函数具有多个随机值? I tested for only one value: 我只测试了一个值:

Random rand=new Random();
int min=0, max=10;
int valeur = rand.nextInt(max - min + 1) + min;

The simplest way to get random but distinct values is to use shuffle. 获得随机但不同的值的最简单方法是使用随机播放。

List<Integer> list = new ArrayList<>();
for(int i = min; i <= max; i++) list.add(i);
Collections.shuffle(list);

You can iterate over list and get unique numbers in a random order. 您可以遍历list并以随机顺序获取唯一编号。

You can even using this approach if you want not more than two of something and three of something else by adding the number you wan to the list. 如果您想要的东西不超过两个而其他不超过三个,甚至可以通过将所需的数字添加到列表中来使用此方法。

BTW: This approach is O(n) for n numbers whereas generating random numbers and checking if they are there already is O(n^2 * log(n)) which is much slower. 顺便说一句:对于n个数,此方法为O(n),而生成随机数并检查它们是否已存在,则O(n ^ 2 * log(n))的速度要慢得多。

If I understood your question right, you are trying to obtain a "random" array. 如果我正确理解您的问题,则您正在尝试获取“随机”数组。 If so, you can use the following: 如果是这样,您可以使用以下方法:

int nrOfValues = 20;
int[] values = new int[nrOfValues];
for(int i = 0; i < values.length; i++)
{
    values[i] = rand.nextInt(max - min + 1) + min;
}

If you would like to obtain distinct random values, try the following: 如果要获取不同的随机值,请尝试以下操作:

ArrayList<Integer> values = new ArrayList<Integer>();
int nrOfValues = 20;
for(int i = 0; i < values.length; i++)
{
    int value = rand.nextInt(max - min + 1) + min;
    while(values.contains(value))
        value = rand.nextInt(max - min + 1) + min;
    values.add(value);
}

Of course, if min and max are poorly chosen, you might end up with an infinite loop... 当然,如果minmax的选择不当,您可能会陷入无限循环...

This will prevent numbers being used twice and will get 20%: 这样可以防止数字被使用两次,并获得20%的收益:

    int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    Random random = new Random();

    int numsFound = 0;
    int twentyPercent = (int)(nums.length/5F);
    List<Integer> usedIndices = new ArrayList<Integer>();
    while (numsFound < twentyPercent) {
        int index = random.nextInt(nums.length);

        if (!usedIndices.contains(index)) { // not already used?
            System.out.println(nums[index]);
            usedIndices.add(index);
            numsFound++;
        }
    }

Try This. 尝试这个。

import java.util.Random;
public class Dice 
{
    public static void main(String[] args)
    {
        // Initialize Variables and Array
        Random rand = new Random();
        int[] numbers = new int[10];
        int min = 0, max = 10;


        // Input Random Number Into 10 Elements Of Array
        for (int i = 0; i < numbers.length; i++)
            numbers[i] = rand.nextInt(max - min + 1) + min;


        // Output 10 Array Cells
        for (int i = 0; i < numbers.length; i++)
            System.out.println(numbers[i]);
    }
}

I didnt quite understand the question.. 我不太明白这个问题。

from what i understood you need something like this 据我了解,你需要这样的东西

List<Integer> listOfRandomNumbers = new ArrayList<Integer>();
//Initialize this List with required numbers

int numberOfRandomNumbersNeeded = listOfRandomNumbers/5;
int min = 0; 
int max = listOfRandomNumbers.size() - 1;

Random rand = new Random();
Set<Integer> randomNumbers = new HashSet<Integer>();
while(randomNumbers.size() < numberOfRandomNumbersNeeded) {
int value = rand.nextInt(max - min + 1) + min;
randomNumbers.add(listOfRandomNumbers.get(value));
}

System.out.println(randomNumbers);
private Integer[] recover(double percentage, Integer[] ints) {
    int numberOfElementsToRecover = (int) (ints.length*percentage);
    List<Integer> list = Arrays.asList(ints);
    Collections.shuffle(list);
    return Arrays.copyOfRange(list.toArray(new Integer[]{}), 0, numberOfElementsToRecover);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM