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

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

有什么函数可以做到吗?


当前回答

使用ArrayList<Integer>可以帮助您解决洗牌问题,而无需应用大量逻辑和消耗更少的时间。以下是我的建议:

ArrayList<Integer> x = new ArrayList<Integer>();
for(int i=1; i<=add.length(); i++)
{
    x.add(i);
}
Collections.shuffle(x);

其他回答

下面的代码将实现数组的随机排序。

// Shuffle the elements in the array
Collections.shuffle(Arrays.asList(array));

来自:http://www.programcreek.com/2012/02/java-method-to-shuffle-an-int-array-with-random-order/

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

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>),它受到了影响。

public class ShuffleArray {
public static void shuffleArray(int[] a) {
    int n = a.length;
    Random random = new Random();
    random.nextInt();
    for (int i = 0; i < n; i++) {
        int change = i + random.nextInt(n - i);
        swap(a, i, change);
    }
}

private static void swap(int[] a, int i, int change) {
    int helper = a[i];
    a[i] = a[change];
    a[change] = helper;
}

public static void main(String[] args) {
    int[] a = new int[] { 1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1 };
    shuffleArray(a);
    for (int i : a) {
        System.out.println(i);
    }
}
}

Groovy的一个简单解决方案:

solutionArray.sort{ new Random().nextInt() }

这将对数组列表中的所有元素进行随机排序,存档所有元素洗牌的预期结果。

类似的情况没有使用swap b

    Random r = new Random();
    int n = solutionArray.length;
    List<Integer> arr =  Arrays.stream(solutionArray)
                               .boxed()
                               .collect(Collectors.toList());
    for (int i = 0; i < n-1; i++) {
        solutionArray[i] = arr.remove(r.nextInt(arr.size())); // randomize based on size
    }
    solutionArray[n-1] = arr.get(0);