我从java开始,遇到问题
我需要创建具有相同随机值的2个数组,但这些值必须按不同顺序排列,如下所示:
int[] firstArray= {5, 12, 7, 10, 6, 8};
int[] secondArray= {12, 7, 8, 5, 10, 6};
但我希望随机数字。我怎样才能做到这一点 ?感谢
答案 0 :(得分:1)
如果您不想定义自己的库,那么您可以使用随机播放的方法。
String[] alpha = { "A", "E", "I", "O", "U" };
List list = new ArrayList(alpha);
Collections.shuffle(list);
String[] shuffledAlpha = list.toArray();
答案 1 :(得分:0)
试试这个
public static int[] RandArray(int[] array){
Random rand = new Random();
for (int i=0; i<array.length; i++) {
int randomPosition = rand.nextInt(array.length);
int temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
return array;
}
在主要添加此
int[] firstArray = {5, 12, 7, 10, 6, 8};
int[] secondArray = RandArray(firstArray);
for (int i = 0; i < secondArray.length; i++)
{
System.out.print(secondArray[i] + " ");
}
System.out.println();
这是输出:
7 8 10 6 12 5
要随机化firstArray,请添加以下代码:
public static int[] RandFirstArray(int arraySize, int min, int max){
Random rand = new Random();
int[] firstArray = new int[arraySize];
for (int i=0; i<arraySize; i++) {
firstArray[i] = rand.nextInt((max - min) + 1) + min;
}
return firstArray;
}
比主要:
//Use RandFirstArray(ArrayLength, MinValue, MaxValue)
int[] firstArray = RandFirstArray(6, 0 , 20);
System.out.println("First Array\n");
for (int i = 0; i < firstArray.length; i++)
{
System.out.print(firstArray[i] + " ");
}
System.out.println("\n\nSecond Array\n");
int[] secondArray = RandArray(firstArray);
for (int i = 0; i < secondArray.length; i++)
{
System.out.print(secondArray[i] + " ");
}
System.out.println();
新输出:
First Array
3 20 5 13 8 11
第二阵列
8 13 11 20 3 5
答案 2 :(得分:0)
使用此方法,使用Fisher-Yates shuffle。
{{3}}
public int[] 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];
}
}
return array;
}