我需要随机洗牌以下数组:

int[] solutionArray = {1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1};

有什么函数可以做到吗?


当前回答

其中一种解决方法是使用排列来预先计算所有的排列并存储在数组列表中

Java 8在Java .util. random类中引入了一个新方法ints()。ints()方法返回无限的伪随机int值流。您可以通过提供最小值和最大值来限制指定范围内的随机数。

Random genRandom = new Random();
int num = genRandom.nextInt(arr.length);

在生成随机数的帮助下,您可以遍历循环并与随机数交换当前索引。 这就是生成空间复杂度为O(1)的随机数的方法。

其他回答

下面是使用集合的完整解决方案。洗牌的方法:

public static void shuffleArray(int[] array) {
  List<Integer> list = new ArrayList<>();
  for (int i : array) {
    list.add(i);
  }

  Collections.shuffle(list);

  for (int i = 0; i < list.size(); i++) {
    array[i] = list.get(i);
  }    
}

请注意,由于Java无法在int[]和Integer[]之间平滑转换(因此int[]和List<Integer>),它受到了影响。

下面是数组的泛型版本:

import java.util.Random;

public class Shuffle<T> {

    private final Random rnd;

    public Shuffle() {
        rnd = new Random();
    }

    /**
     * Fisher–Yates shuffle.
     */
    public void shuffle(T[] ar) {
        for (int i = ar.length - 1; i > 0; i--) {
            int index = rnd.nextInt(i + 1);
            T a = ar[index];
            ar[index] = ar[i];
            ar[i] = a;
        }
    }
}

考虑到ArrayList基本上只是一个数组,使用ArrayList而不是显式数组并使用Collections.shuffle()可能是明智的。但是,性能测试并没有显示上述方法与Collections.sort()之间有任何显著差异:

Shuffe<Integer>.shuffle(...) performance: 576084 shuffles per second
Collections.shuffle(ArrayList<Integer>) performance: 629400 shuffles per second
MathArrays.shuffle(int[]) performance: 53062 shuffles per second

Apache Commons实现MathArrays。Shuffle限制为int[],性能损失可能是由于使用了随机数生成器。

这是knuth shuffle算法。

public class Knuth { 

    // this class should not be instantiated
    private Knuth() { }

    /**
     * Rearranges an array of objects in uniformly random order
     * (under the assumption that <tt>Math.random()</tt> generates independent
     * and uniformly distributed numbers between 0 and 1).
     * @param a the array to be shuffled
     */
    public static void shuffle(Object[] a) {
        int n = a.length;
        for (int i = 0; i < n; i++) {
            // choose index uniformly in [i, n-1]
            int r = i + (int) (Math.random() * (n - i));
            Object swap = a[r];
            a[r] = a[i];
            a[i] = swap;
        }
    }

    /**
     * Reads in a sequence of strings from standard input, shuffles
     * them, and prints out the results.
     */
    public static void main(String[] args) {

        // read in the data
        String[] a = StdIn.readAllStrings();

        // shuffle the array
        Knuth.shuffle(a);

        // print results.
        for (int i = 0; i < a.length; i++)
            StdOut.println(a[i]);
    }
}

我在一些答案中看到了一些遗漏的信息,所以我决定添加一个新的。

Java集合数组。asList接受类型为T的var-arg (T…)。如果传递一个基元数组(int array), asList方法将推断并生成一个List<int[]>,这是一个单元素列表(其中一个元素是基元数组)。如果你洗牌这个元素列表,它不会改变任何东西。

首先,你需要将原始数组转换为Wrapper对象数组。为此,您可以使用ArrayUtils。apache.commons.lang中的一个对象方法。然后将生成的数组传递给一个List,最后洗牌。

  int[] intArr = {1,2,3};
  List<Integer> integerList = Arrays.asList(ArrayUtils.toObject(array));
  Collections.shuffle(integerList);
  //now! elements in integerList are shuffled!

在Java中,我们可以使用集合。Shuffle方法随机重新排列列表中的项目。

Groovy 3.0.0直接将shuffle和shuffle方法添加到List或数组中。