我需要随机洗牌以下数组:
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};
有什么函数可以做到吗?
当前回答
import java.util.ArrayList;
import java.util.Random;
public class shuffle {
public static void main(String[] args) {
int a[] = {1,2,3,4,5,6,7,8,9};
ArrayList b = new ArrayList();
int i=0,q=0;
Random rand = new Random();
while(a.length!=b.size())
{
int l = rand.nextInt(a.length);
//this is one option to that but has a flaw on 0
// if(a[l] !=0)
// {
// b.add(a[l]);
// a[l]=0;
//
// }
//
// this works for every no.
if(!(b.contains(a[l])))
{
b.add(a[l]);
}
}
// for (int j = 0; j <b.size(); j++) {
// System.out.println(b.get(j));
//
// }
System.out.println(b);
}
}
其他回答
下面是数组的泛型版本:
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[],性能损失可能是由于使用了随机数生成器。
其中一种解决方法是使用排列来预先计算所有的排列并存储在数组列表中
Java 8在Java .util. random类中引入了一个新方法ints()。ints()方法返回无限的伪随机int值流。您可以通过提供最小值和最大值来限制指定范围内的随机数。
Random genRandom = new Random();
int num = genRandom.nextInt(arr.length);
在生成随机数的帮助下,您可以遍历循环并与随机数交换当前索引。 这就是生成空间复杂度为O(1)的随机数的方法。
最简单的洗牌代码:
import java.util.*;
public class ch {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
ArrayList<Integer> l=new ArrayList<Integer>(10);
for(int i=0;i<10;i++)
l.add(sc.nextInt());
Collections.shuffle(l);
for(int j=0;j<10;j++)
System.out.println(l.get(j));
}
}
下面是一个使用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-
Groovy的一个简单解决方案:
solutionArray.sort{ new Random().nextInt() }
这将对数组列表中的所有元素进行随机排序,存档所有元素洗牌的预期结果。