我有一个数组:
int arr[] = {1, 2, 3, 4}
如何将arr[]
随机化为无重复的多列表?
这
arr[] = { 1, 2, 3, 4 }
要
arr1[] = {1, 2, 3, 4}
arr2[] = {2, 1, 4, 3}
arr3[] = {3, 4, 1, 2}
arr4[] = {4, 3, 2, 1}
答案 0 :(得分:0)
在这种情况下,最好使用List<Integer>
代替int[]
List<Integer> arr = new ArrayList<Integer>();
Random random = new Random();
int randonint = arr.remove(random.nextint(arr.getSize()));
每次运行此代码时,它都会从列表arr
中获取一个随机int,然后您可以将其添加到不同的List / Array
因此,如果您想从一个列表中获取所有值,并将它们随机放入其他3个列表,请使用以下代码:
List<Integer> arr1 = new ArrayList<Integer>();
List<Integer> to1 = new ArrayList<Integer>();
List<Integer> to2 = new ArrayList<Integer>();
List<Integer> to3 = new ArrayList<Integer>();
Random random = new Random();
for (int i = 1 ; i <= 10 ; i++) {
arr1.add(i);
}
for (int count = 0 ; count < arr1.size() ; count++) {
List<Integer> arr = new ArrayList<Integer>();
int randomvalue = arr.remove(random.nextint(arr.getSize()));
switch (random.nextInt(3)) {
case 0:
to1.add(randomvalue);
case 1:
to2.add(randomvalue);
case 2:
to2.add(randomvalue);
}
}
答案 1 :(得分:0)
public static void GenerateRandomArray()
{
var inputArray = new[] {1, 2, 3, 4};
var outputArray = GetRandomArray(inputArray);
PrintArray(outputArray);
}
private static void PrintArray(int[,] outputArray)
{
for (var i = 0; i < outputArray.GetLength(0); i += 1)
{
for (var j = 0; j < outputArray.GetLength(1); j += 1)
{
Console.Write(outputArray[i, j]);
}
Console.WriteLine();
}
}
private static int[,] GetRandomArray(int[] inputArray)
{
var lengthOfArray = inputArray.Length;
var outputArray = new int[lengthOfArray,lengthOfArray];
for (var i = 0; i < lengthOfArray; i++)
{
var counterShifter = i;
for (var j = 0; j < lengthOfArray;j++)
{
outputArray[i, j] = inputArray[counterShifter];
counterShifter = counterShifter + 1 < lengthOfArray
? counterShifter + 1 :
0;
}
}
return outputArray;
}