I want to generate in java an array with random numbers from 1 to 10 but I need the array to have at least one of each 10 numbers.
wrong: array = {1,2,3,1,3,2,4,5}
correct: array = {1,2,4,3,6,8,7,9,5,10...}
The array can have size bigger than 10 but the 0 to 10 numbers must exist in the array.
My code for generating the array so far:
public int[] fillarray(int size, int Reel[]) {
for (int i = 0; i < size; i++) {
Reel[i] = (int) (Math.random() * symbols);
}
System.out.println(Arrays.toString(Reel));
return Reel;
}
答案 0 :(得分:10)
You can use a List
and Collections.shuffle
:
List<Integer> list = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
Collections.shuffle(list);
And, following @Elliott's helpful advice, you can convert a list to array:
int[] result = list.stream().mapToInt(Integer::intValue).toArray();