如何在java中生成列表/数组的随机紊乱?

我在实现返回大小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]


阿晨1998
浏览 124回答 2
2回答

海绵宝宝撒

这个想法是在集合中有N个元素,你会从中选择数字,直到它被耗尽。类似的东西List<Integer> temp = IntStream.range(0, 6).boxed().collect(Collectors.toList());int[] array = new int[6];while (temp.size() > 0) {&nbsp; &nbsp; int rndIndex = ThreadLocalRandom.current().nextInt(temp.size());&nbsp; &nbsp; array[temp.size() - 1] = temp.get(rndIndex);&nbsp; &nbsp; temp.remove(rndIndex);}System.out.println(Arrays.toString(array)); // could be [4, 5, 3, 2, 1, 0]如果您不想使用临时列表,则可以这样做,但这需要更多的代码。这个想法是一样的。

慕村9548890

使用排序地图怎么样,你的键将是随机的,就像这样:public static int[] derangement(int n){&nbsp; &nbsp; Random rand = new Random();&nbsp; &nbsp; int[] result = new int[n];&nbsp; &nbsp; SortedMap<Double, Integer> map = new TreeMap<>();&nbsp; &nbsp; for (int i = 0; i < n; i++) {&nbsp; &nbsp; &nbsp; &nbsp; map.put(rand.nextDouble(), i);&nbsp; &nbsp; }&nbsp; &nbsp; int i = 0;&nbsp; &nbsp; for (Double key: map.keySet()) {&nbsp; &nbsp; &nbsp; &nbsp; result[i] = map.get(key);&nbsp; &nbsp; &nbsp; &nbsp; i++;&nbsp; &nbsp; }&nbsp; &nbsp; return result;}这样,当地图中的随机键变为有序时,您将对列表进行随机排序。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java