Reputation: 219
I want to generate random integers from range 0-9 and put it in an array of size 100. That's easy but I'm clueless on how to make sure that in the array, I have at least one occurrence of every integer in the range 0-9.
This is all using java by the way.
This is what I've got so far (the numbers are different in my coding because I wanted to ask a simpler question):
public static int[] extendTo1024(int[] key) {
int[] extendedKey = new int[1024];
Random random = new Random();
for(int i = 0; i < 1024; i++) {
int rand = random.nextInt(64) + 1;
extendedKey[i] = bitKey[rand];
}
return extendedKey;
}
Any help? Thank you in advance!
Upvotes: 0
Views: 161
Reputation: 1668
ArrayList<Integer> al = new ArrayList<Integer>();
//make sure the array contains all occurences of 0-9
for (int i = 0; i < 10; i++) {
al.add(i, i);
}
//generate random number for the remaining 90
for (int i = 10; i < 100; i++) {
int random = (int) (Math.random() * 10);
al.add(i, random);
}
//shuffle the random numbers to make sure that the first 10 are randomly placed
Collections.shuffle(al);
//Convert it back to array (In case you need it to be array not ArrayList)
Integer[] randomNums = al.toArray(new Integer[100]);
//result
for (int i : randomNums) {
System.out.println(i);
}
Upvotes: 1
Reputation: 2571
Upvotes: 3