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

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

有什么函数可以做到吗?


当前回答

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

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!

其他回答

Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--)
{
  int index = rnd.nextInt(i + 1);
  // Simple swap
  int a = ar[index];
  ar[index] = ar[i];
  ar[i] = a;
}

顺便说一下,我注意到这段代码返回了一个ar.length - 1个数的元素,所以如果你的数组有5个元素,新的打乱的数组将有4个元素。这是因为for循环说i>0。如果你改变为i>=0,你得到所有的元素洗牌。

最简单的解决方案,这种随机洗牌数组。

String location[] = {"delhi","banglore","mathura","lucknow","chandigarh","mumbai"};
int index;
String temp;
Random random = new Random();
for(int i=1;i<location.length;i++)
{
    index = random.nextInt(i+1);
    temp = location[index];
    location[index] = location[i];
    location[i] = temp;
    System.out.println("Location Based On Random Values :"+location[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!

下面是一个有效的Fisher-Yates shuffle数组函数:

private static void shuffleArray(int[] array)
{
    int index;
    Random random = new Random();
    for (int i = array.length - 1; i > 0; i--)
    {
        index = random.nextInt(i + 1);
        if (index != i)
        {
            array[index] ^= array[i];
            array[i] ^= array[index];
            array[index] ^= array[i];
        }
    }
}

or

private static void shuffleArray(int[] array)
{
    int index, temp;
    Random random = new Random();
    for (int i = array.length - 1; i > 0; i--)
    {
        index = random.nextInt(i + 1);
        temp = array[index];
        array[index] = array[i];
        array[i] = temp;
    }
}

你现在可以使用java 8了:

Collections.addAll(list, arr);
Collections.shuffle(list);
cardsList.toArray(arr);