我需要随机洗牌以下数组:
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};
有什么函数可以做到吗?
当前回答
无随机解:
static void randomArrTimest(int[] some){
long startTime = System.currentTimeMillis();
for (int i = 0; i < some.length; i++) {
long indexToSwap = startTime%(i+1);
long tmp = some[(int) indexToSwap];
some[(int) indexToSwap] = some[i];
some[i] = (int) tmp;
}
System.out.println(Arrays.toString(some));
}
其他回答
类似的情况没有使用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);
最简单的解决方案,这种随机洗牌数组。
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]);
}
使用Guava的int . aslist()就像这样简单:
Collections.shuffle(Ints.asList(array));
其中一种解决方法是使用排列来预先计算所有的排列并存储在数组列表中
Java 8在Java .util. random类中引入了一个新方法ints()。ints()方法返回无限的伪随机int值流。您可以通过提供最小值和最大值来限制指定范围内的随机数。
Random genRandom = new Random();
int num = genRandom.nextInt(arr.length);
在生成随机数的帮助下,您可以遍历循环并与随机数交换当前索引。 这就是生成空间复杂度为O(1)的随机数的方法。
看看Collections类,特别是shuffle(…)。