Tony
Tony

Reputation: 219

Generate Random Numbers In A Range with All Numbers Being Hit

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

Answers (2)

lxcky
lxcky

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

SnakE
SnakE

Reputation: 2571

  1. Fill the first 10 elements with numbers 0-9
  2. Fill the rest with random numbers
  3. Shuffle the array

Upvotes: 3

Related Questions