不要在java中重复随机数

时间:2014-08-23 00:30:22

标签: java

我怎么能让我的代码不重复随机生成的任何数字,在论坛中查找但找不到任何我能够轻易理解的例子。

import java.util.*;
public class Lottery {
    public static void main(String[] args) {
       int n[] = {37};
       Random rd = new Random();
       for (int i = 0; i < n.length;i++){
            for (int j=0; j <6;j++) {
                System.out.println(rd.nextInt(n[i])+1); 
            }   
       }
    }
}

5 个答案:

答案 0 :(得分:1)

您想要N个数字的随机排列。所以,你创建一个int []并用0 ... max填充它,然后你将它洗牌。几个开源库提供随机shuffle /置换方法。

答案 1 :(得分:1)

如果你有一个非常广泛的数字(超过10,000),并根据你需要的数量, 将滚动的数字放入一组。如果密钥存在,请重新滚动该随机数,就像AntonH建议的那样。

但是,如果您有一些数字且滚动很多次,那么您点击已滚动值的次数就会变得很大。

在这种情况下,请将所需的可能数字存储在列表中,然后将其随机播放。

ArrayList<Integer> numbers = new ArrayList<Integer>(10); 
for (int i = 0; i < numbers.size(); i++) { 
    numbers.add(i); 
} 
Collections.shuffle(numbers);

然后按顺序访问列表中的每个随机数。

答案 2 :(得分:1)

在编写模拟现实生活对象的程序时,请使用现实生活中使用的相同方法。

在彩票中你有一套有序的球,这些球都是洗牌的。

因此,创建一个数组,并用1到maxNumber的数字填充它。

然后使用类Collections及其方法shuffle来重新排列此数组。

那就是它。

答案 3 :(得分:1)

您希望从一组m项中随机抽取n项。你可以创建一个简单的 Draw类如下所示,并将其称为“m”次以获取项目的连续索引。

package com.example.randomdraw;

import java.util.ArrayList;
import java.util.Random;

public class Draw {
    private Random random = null;
    private ArrayList<Integer> list = new ArrayList<Integer>();

    public Draw(int n) {
        // Make sure list was initialized and items remain
        if (list == null || list.size() < 1) {
             return -1;
        ?
        random = new Random();
        // Establish a list of indexes to be used in returning a draw
        for (int i=0; i<n; i++) {
            list.add(i);
        }
    }
    // return the next random index from the m numbers(0 to m-1)
    public int getNextDraw() {
        // get random number from 0 to the number of remaining items
        int i = random.nextInt(list.size());
        // get the value to return (the ith element from the remaining items
        int result = list.get(i);
        // remove the item to be returned, so it won't be available to draw
        list.remove(i);
        // return the requested result
        return result;
    }
}

答案 4 :(得分:0)

这是一个实现,只要它与之前的数字相同,就会随机执行下一步:

public class UniqueRandom {
    private Random random = new Random();
    private Set<Integer> usedNumbers = new HashSet(); 

    public int nextInt() {
        int potentialRandom = this.random.nextInt();

        // try while we don't find unique random
        while (this.usedNumbers.contains(potentialRandom)) {
            potentialRandom = this.random.nextInt();
        }

        // reserve found unique random number
        this.usedNumbers.add(potentialRandom);

        return potentialRandom;
    }
}

基本用法如下:

    UniqueRandom uniqueRandom = new UniqueRandom();
    for (int i = 0; i < 20; i++) {
        System.out.println(uniqueRandom.nextInt());
    }
相关问题