我需要随机洗牌以下数组:
int[] solutionArray = {1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1};
有什么函数可以做到吗?
我需要随机洗牌以下数组:
int[] solutionArray = {1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1};
有什么函数可以做到吗?
当前回答
下面的代码将实现数组的随机排序。
// 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/
其他回答
看看Collections类,特别是shuffle(…)。
下面是使用集合的完整解决方案。洗牌的方法:
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>),它受到了影响。
下面是一个使用Apache Commons Math 3的解决方案。X(仅适用于int[]数组):
MathArrays.shuffle(array);
http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/util/MathArrays.html shuffle (int [])
另外,Apache Commons Lang 3.6为ArrayUtils类引入了新的shuffle方法(用于对象和任何基本类型)。
ArrayUtils.shuffle(array);
http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/ArrayUtils.html#shuffle-int:A-
使用集合来洗牌一个基本类型数组有点过分……
你自己实现这个函数很简单,比如使用Fisher-Yates shuffle:
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
class Test
{
public static void main(String args[])
{
int[] solutionArray = { 1, 2, 3, 4, 5, 6, 16, 15, 14, 13, 12, 11 };
shuffleArray(solutionArray);
for (int i = 0; i < solutionArray.length; i++)
{
System.out.print(solutionArray[i] + " ");
}
System.out.println();
}
// Implementing Fisher–Yates shuffle
static void shuffleArray(int[] ar)
{
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = ThreadLocalRandom.current();
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;
}
}
}
最简单的解决方案,这种随机洗牌数组。
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]);
}