亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在java中生成列表/數組的隨機紊亂?

如何在java中生成列表/數組的隨機紊亂?

阿晨1998 2022-09-07 20:53:57
我在實現返回大小n的隨機紊亂的方法時遇到問題。我不確定我的代碼出了什么問題,我需要幫助找出邏輯上錯誤的地方。這是針對一個小程序,我只是想寫,但在可視化邏輯流時遇到問題。我嘗試過更改 while 循環的條件,但到目前為止,我嘗試過的任何方法都不起作用。我也嘗試過使用列表和數組列表來實現,但是當我試圖將其放入代碼中時,它變得有點太復雜了。有沒有更簡單的方法可以做到這一點?public static int[] derangement(int n){    int[] arr1 = new int[n];    int[] arr2 = new int[n];    //second array is to keep track of which positions are 'taken' to prevent collision    Random rand = new Random();    int temp = -1;    for(int i =0; i <n; i++){        arr1[i] = i;    }    for(int k=0;k<n;k++){        arr2[k] = -1;    }    for(int j=0;j<n;j++){        temp = j;        while (temp == j || arr2[j] != -1){            temp = rand.nextInt(n); //generate a random number until it gives one that hasn't been used before            if(arr2[temp] == -1){                arr2[temp] = j;            }        }    }    return arr2;}我期望輸出為 [2,4,1,5,3,0] 對于 n = 6,但我只是得到 [-1,-1,-1,-1,-1,-1,-1,-1]
查看完整描述

2 回答

?
海綿寶寶撒

TA貢獻1809條經驗 獲得超8個贊

這個想法是在集合中有N個元素,你會從中選擇數字,直到它被耗盡。類似的東西


List<Integer> temp = IntStream.range(0, 6).boxed().collect(Collectors.toList());

int[] array = new int[6];

while (temp.size() > 0) {

    int rndIndex = ThreadLocalRandom.current().nextInt(temp.size());

    array[temp.size() - 1] = temp.get(rndIndex);

    temp.remove(rndIndex);

}

System.out.println(Arrays.toString(array)); // could be [4, 5, 3, 2, 1, 0]

如果您不想使用臨時列表,則可以這樣做,但這需要更多的代碼。這個想法是一樣的。


查看完整回答
反對 回復 2022-09-07
?
慕村9548890

TA貢獻1884條經驗 獲得超4個贊

使用排序地圖怎么樣,你的鍵將是隨機的,就像這樣:


public static int[] derangement(int n){

    Random rand = new Random();

    int[] result = new int[n];

    SortedMap<Double, Integer> map = new TreeMap<>();

    for (int i = 0; i < n; i++) {

        map.put(rand.nextDouble(), i);

    }

    int i = 0;

    for (Double key: map.keySet()) {

        result[i] = map.get(key);

        i++;

    }

    return result;

}

這樣,當地圖中的隨機鍵變為有序時,您將對列表進行隨機排序。


查看完整回答
反對 回復 2022-09-07
  • 2 回答
  • 0 關注
  • 107 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號