5 Replies Latest reply on Jul 26, 2013 7:08 AM by e697c280-00bc-47ab-a0c8-c131b4db31be

# How to generate 10 DIFFERENT random numbers?

I'm trying to fill an ArrayList with ten different random numbers (out of 20 numbers). I just can't seem to get it right. I've tried many things and I think I'm drifting farther away from the solution as I go on.

Two requests:

1) An efficient way to do this.
2) Point out what goes wrong with my incorrect approach so I learn something.

THANK YOU!

The last approach I came up with looks like this. But the loop never ends...

import java.util.ArrayList;
import java.util.Random;

public class RandomDifferent {
public static void main(String args[]) {

Random randomNumber = new Random();
int random;

ArrayList<Integer> b = new ArrayList<Integer>();

while (b.size() < 10) {
for (int y=0; y<10; y++) {
random = randomNumber.nextInt(20);
for (int i = 0; i<b.size(); i++) {
if (b.get(i) != random)
}
}
}

for (int y=0; y<b.size(); y++) {
System.out.println(b.get(y));
}

}
}
• ###### 1. Re: How to generate 10 DIFFERENT random numbers?
Collections.shuffle() should help you. Create a list of numbers 0 through 19, shuffle it, and pisck the first ten.
• ###### 2. Re: How to generate 10 DIFFERENT random numbers?
Use code tags if you're going to post code. You can find them next to the quote tags.

import java.util.ArrayList;
import java.util.Random;

public class RandomDifferent {
public static void main(String args[]) {
Random randomNumber = new Random();
int random;

ArrayList<Integer> b = new ArrayList<Integer>();

while (b.size() < 10) { // While not 10 ints in list
for (int y=0; y<10; y++) { // Loop 10 times (why loop 10 times? You're already looping.
random = randomNumber.nextInt(20);
for (int i = 0; i<b.size(); i++) {
// If random number not equal to element at position i, add it
if (b.get(i) != random)
}
}
}

for (int y=0; y<b.size(); y++) {
System.out.println(b.get(y))
}
}
}
So, what happens when your list contains no items? You never enter that inner loop.

If you want 10 unique numbers, you may want to use a Set and then toss the Set's contents into a list once you have the required number count.
• ###### 3. Re: How to generate 10 DIFFERENT random numbers?
Good idea! Thanks!
• ###### 4. Re: How to generate 10 DIFFERENT random numbers?
AH thanks for pointing out the tags! That does look allot better!

I understand whats wrong now. Thanks again!
• ###### 5. Re: How to generate 10 DIFFERENT random numbers?

Spoon feeding code removed.

Mod: I'm locking this zombie now.

Message was edited by: PhHein