从间隔中排除数字,检索其余部分

时间:2014-12-01 23:33:09

标签: java list random

我希望使用随机生成器在0到9之间的数字间隔。例如,如果我已经收到0,2,7我不再想要这些数字,而是我想要在给定间隔[1或3或4或5或6或8或9]之间的其余数字之一。

4 个答案:

答案 0 :(得分:3)

正如鲍里斯蜘蛛所说:

// We want numbers between 0 and 9 inclusive
int min = 0, max = 9; 
// We need a Collection, lets use a List, could use any ordered collection here
List<Integer> nums = new ArrayList<>();
// Put the numbers in the collection
for (int n=min; n<=max; n++) { nums.add(n); }

// Randomly sort (shuffle) the collection
Collections.shuffle(nums);

// Pull numbers from the collection (the order should be random now)
for (int count=0; count<nums.length; count++) {
    System.out.println("Number " + count + " is " + nums.get(count));
}

答案 1 :(得分:0)

此解决方案使用math.random以更好的时间性能运行。

LinkedList<Integer> numbers = new LinkedList<>();
numbers.add(1);
numbers.add(2); //or more

while (!numbers.isEmpty()) {
    System.out.println(numbers.remove((int) (Math.random() * numbers.size())));
}

答案 2 :(得分:0)

使用java 8,您可以执行以下操作

List<Integer> integers = IntStream.range(0, 10).boxed().collect(Collectors.toList());
Collections.shuffle(integers);

如此answer所示。

答案 3 :(得分:-1)

这是Java.util.Collections的替代方法,它使用Java.util.Random类。

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{

    final static int RAND_CAP = 9;

    public static void main (String[] args) throws java.lang.Exception
    {
        ArrayList<Integer> usedNumbers = new ArrayList<Integer>();
        Random rand = new Random(System.currentTimeMillis());
        while (usedNumbers.size() < RAND_CAP) {
            int randNum = Math.abs(rand.nextInt() % RAND_CAP) + 1;
            if (!usedNumbers.contains(randNum)) {
                usedNumbers.add(randNum);
                System.out.println(randNum);
            }
        }
    }
}

run code here