How can I randomly generate a matrix like the one above, where the last element represents the user's number 0-n and the remaining n-1 elements are arbitrary numbers in a random sequence?
Here is another way to do it.
int n = 6;
This defines a simple lambda to
- effectively move the user's number to the end of the array
- shuffle the array, excluding the last element (user's no).
BiFunction<int[],Integer,int[]> shuffle = (ar,ii)->{
int len = ar.length-1;
ar[len] = ar[ii];
ar[ii] = len--;
while (len >= 0) {
int i = (int)(Math.random()*len);
int t = ar[i];
ar[i] = ar[len];
ar[len--]=t;
}
return ar;
};
Now build a single array that goes from 0 to n
.
int[] arr = IntStream.range(0, n).toArray();
Time to shuffle
the array and move
the user to the
end and create the final array of arrays.
int[][] darr = IntStream.range(0, n)
.mapToObj(i -> shuffle.apply(arr.clone(), i))
.toArray(int[][]::new);
Now print them
for (int[] a : darr) {
System.out.println(Arrays.toString(a));
}
For n = 6
, prints
[2, 4, 3, 1, 5, 0]
[2, 4, 5, 0, 3, 1]
[4, 5, 3, 0, 1, 2]
[4, 0, 5, 1, 2, 3]
[5, 3, 0, 2, 1, 4]
[3, 0, 4, 2, 1, 5]