簡體   English   中英

生成特定范圍內的隨機數

[英]Generating random numbers in a particular range

我正在嘗試在我的Android代碼中生成0-31之間的n隨機數。 下面是我正在使用的代碼:

int max_range = 31;
SecureRandom secureRandom = new SecureRandom();
int[] digestCodeIndicesArr = new int[indices_length];
int i = 0, random_temp = 0;

while (i != indices_length-1) {
    random_temp = secureRandom.nextInt(max_range);
    if (!Arrays.asList(digestCodeIndicesArr).contains(random_temp)) {
        digestCodeIndicesArr[i] = random_temp;
        i++;
    }
}

indices_length是我需要的隨機數。 通常是6,7或9。但是當我打印生成的數組時,通常最終會看到重復項。 有人可以指出我犯的錯誤嗎? 我添加了以下代碼行以過濾掉隨機重復項:

if (!Arrays.asList(digestCodeIndicesArr).contains(random_temp))

提前致謝!

Arrays.asList(digestCodeIndicesArr)不會生成具有size() == digestCodeIndicesArr.lengthList<Integer>
它產生一個size() == 1List<int[]> ,其中第一個(也是唯一一個)元素是數組。
因此,它永遠不會包含random_temp ,所以! contains() ! contains()始終為true。

不斷創建列表並執行順序搜索以檢查重復項對性能不利。 而是使用與數組並行維護的Set ,或者先使用LinkedHashSet ,然后轉換為數組。

無論如何,這解釋了為什么您的代碼無法正常工作。 Tunaki提供的重復鏈接以及我在評論中提供的重復鏈接 ,說明了如何實際執行您要執行的操作。

您需要更改:

int[] digestCodeIndicesArr = new int[indices_length];

至:

Integer[] digestCodeIndicesArr = new Integer[indices_length];

因為Arrays.asList(digestCodeIndicesArr)List<int[]> ,而不是您想的那樣(我猜是List<int>List<Integer> )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM