Question:
How to shuffle two random size arrays of numbers into one single array?
Code:
import java.util.*;
public class ShuffleArrays {
public static void main(String[] args) {
Random r = new Random();
int array1[] = new int[r.nextInt(10)];
int array2[] = new int[r.nextInt(10)];
int array3[] = new int[array1.length + array2.length];
System.out.println("array1 size: " + array1.length);
System.out.println("array2 size: " + array2.length);
System.out.println("array3 size: " + array3.length);
// populate array1 & array2 with random numbers
for(int i=0;i<array1.length;i++){
array1[i]=r.nextInt(100);
}
for(int i=0;i<array2.length;i++){
array2[i]=r.nextInt(100);
}
// populate array3 with contents of array1 & array2
for(int i=0;i<array1.length;i++){
array3[i]=array1[i];
}
for(int i=0;i<array2.length;i++){
array3[i+array1.length]=array2[i];
}
System.out.println("array1: " + Arrays.toString(array1));
System.out.println("array2: " + Arrays.toString(array2));
System.out.println("array3: " + Arrays.toString(array3));
// shuffle array3
int temp;
int swapindex;
System.out.println("array3: shuffling");
for(int i=0;i<array3.length;i++){
temp=array3[i];
swapindex=r.nextInt(array3.length);
array3[i]=array3[swapindex];
array3[swapindex]=temp;
}
System.out.println("array3: " + Arrays.toString(array3));
}
}
Output:
$ java ShuffleArrays
array1 size: 9
array2 size: 6
array3 size: 15
array1: [82, 52, 72, 62, 77, 65, 39, 28, 97]
array2: [27, 0, 12, 78, 35, 14]
array3: [82, 52, 72, 62, 77, 65, 39, 28, 97, 27, 0, 12, 78, 35, 14]
array3: shuffling
array3: [72, 39, 77, 82, 27, 78, 62, 97, 12, 0, 35, 65, 14, 52, 28]