无需重复的随机数字随机化的有效方法

时间:2016-10-04 17:28:16

标签: java arrays algorithm random

我已使用此代码将1000000个数字随机化而不重复。这是我到目前为止所拥有的。

enter code here  protected void randomise() {
    int[] copy = new int[getArray().length];
    // used to indicate if elements have been used
    boolean[] used = new boolean[getArray().length];
    Arrays.fill(used,false);
    for (int index = 0; index < getArray().length; index++) {
        int randomIndex;
        do {
            randomIndex = getRandomIndex();
        } while (used[randomIndex]);
        copy[index] = getArray()[randomIndex];
        used[randomIndex] = true;
    }
    for (int index = 0; index < getArray().length; index++) {
        getArray()[index] = copy[index];
        //Checks if elements in array have already been used
    }
}

public static void main(String[] args) {
    RandomListing count = new SimpleRandomListing(1000000);
    //Will choose 1000000 random numbers
    System.out.println(Arrays.toString(count.getArray()));
}

这个方法太慢你能不能让我知道如何更有效地完成这项工作。我感谢所有的回复。 的问候,

2 个答案:

答案 0 :(得分:0)

更有效的方法是从一个数字池(例如0到1000000之间的所有数字的 <div class="varietyTypeName" data-toggle="collapse" data-target="" aria-expanded="true" aria-controls=""> Greens <i class="fa fa-angle-down arrow-toggle"></i> </div> <div class="collapse in collapsableArea"> <div class="varietyFamilyName">Arugula</div> <div class="varietyName"> <a class="ajax-rep rep-main-col" href="/Plan/Selling/DetailsPPVS/5409">Astro</a> <a href="#deleteVarietySelling" id="deleteVarietySelling_5409" class="quick-delete fa-minus-button" title="Delete" data-toggle="modal"> <i class="fa fa-minus"></i> </a> </div> </div> <div class="collapse in collapsableArea"> <div class="varietyFamilyName">Kale</div> <div class="varietyName"> <a class="ajax-rep rep-main-col" href="/Plan/Selling/DetailsPPVS/3720">Kalettes</a> <a href="#deleteVarietySelling" id="deleteVarietySelling_3720" class="quick-delete fa-minus-button" title="Delete" data-toggle="modal"> <i class="fa fa-minus"></i> </a> </div> </div> )开始,然后删除您已经使用过的数字。这样,每当你试图获得一个新号码时,这个号码就可以保证以前从未使用过,而不是花时间去寻找一个好的&#34;未使用的号码。

答案 1 :(得分:0)

看起来您使用线性搜索来查找匹配项。尝试使用二进制搜索更有效。必须对要搜索的数组进行排序以实现二进制搜索。