Reputation: 1564
I want to generate unique random numbers from range 0 to 999,999
.
In order to achieve that, I tried:
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 999999; i++) {
list.add(new Integer(i)); // Add numbers from 0 - 999,999 into ArrayList
}
Collections.shuffle(list); // shuffle them
for (int i = 0; i < 10; i++) {
System.out.println(list.get(i)); // printed unique numbers
}
The problem is the larger the number I want to generate, the longer the time it takes, for the above method, it took about 700ms
.
But if I use Random()
to generate them without filter duplicate numbers, it only takes 2ms
for(int i = 0; i<10; i++) {
int digit = 0 + new Random().nextInt((999999 - 0) + 1);
System.out.println(digit);
}
Is there other way to generate unique random numbers in a more efficient manner?
Upvotes: 1
Views: 1790
Reputation: 136
here is my code
its work perfect
private int count;
private boolean in = true;
public static final Random gen = new Random();
int[] result;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public void addUse() {
result = new int[getCount() + 10];
for (int i = 1; i < 10; i++) {
String setup = ("" + i + i + i + i + i);
result[getCount() + i] = Integer.valueOf(setup);
}
}
public boolean chechArray(int number) {
for (int i = 0; i < getCount() + 10; i++) {
if (result[i] == number) {
in = true;
break;
} else {
in = false;
}
}
return in;
}
public void printRandomNumbers() {
Random gen = new Random();
for (int i = 0; i < getCount(); i++) {
int get = gen.nextInt(100000 - 10000) + 10000;
if (chechArray(get) == false) {
result[i] = get;
} else {
i--;
}
}
}
public void viewArray() {
printRandomNumbers();
for (int i = 0; i < getCount(); i++) {
System.out.println((i + 1) + " Number is = " + result[i]);
}
}
public static void main(String[] args) {
RandomDemo3 rd2 = new RandomDemo3();
rd2.setCount(20);
rd2.addUse();
rd2.viewArray();
}
Upvotes: 0
Reputation: 37655
There is no need to create a list of 1000000 numbers and shuffle them all if you only need 10. There is also no need to write new Integer(i)
(you can just use i
).
In Java 8 there is a very short way to do this:
int[] arr = ThreadLocalRandom.current().ints(0, 1000000).distinct().limit(10).toArray();
System.out.println(Arrays.toString(arr));
If you are using Java 7 or below, you could do this:
Random rand = new Random(); // Only do this in Java 6 or below. Now you should use ThreadLocalRandom.current().
int[] arr = new int[10];
Set<Integer> set = new HashSet<Integer>();
for (int index = 0, a; index < 10;)
if (set.add(a = rand.nextInt(1000000)))
arr[index++] = a;
System.out.println(Arrays.toString(arr));
Upvotes: 5
Reputation: 4976
You could create a set of random integers like this:
Set<Integer> set = new HashSet<Integer>();
Random rand = new Random();
while (set.size() < 10) {
set.add(rand.nextInt((1000000)));
}
The idea is that the set data structure will remove duplicates.
Upvotes: 4