2014-12-01 17 views
0

我想要使用隨機生成器在0和9之間的數字區間。例如,如果我已經收到0,2,7我不想再次使用這些數字,而是希望在給定間隔[1或3或4或5或6或8或9]之間休息一次。從區間中排除數字,檢索其餘區域

+5

這不是隨機的。你想在'Collection'中把數字'[1,9]'洗牌。從頂部拉。 – 2014-12-01 23:36:00

回答

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

這是一種替代方法來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

+0

由於性能隨着達到所需數字的末尾而下降,因此這非常糟糕。事實上,沒有理由讓第二個數字返回 - 「random.nextInt」可以返回相同的數字。進一步'List.contains'是'O(n)','Set.contains'是'O(1)'。這個答案顯示了對程序性隨機性和Java集合API的基本誤解。 – 2014-12-02 08:17:37

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()))); 
} 
0

與Java 8,你可以做以下

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

如該answer所示。