People often want to generate n unique random numbers, say for a lottery application or something. One way to do that is using a set, as below. Just be careful what values you feed into the 'business' method below or you could be waiting a long time for it to return - if it ever does. The source is HERE
import java.util.HashSet;
import java.util.Set;
public class NRand {
/**
* For testing
*/
public static void main(String[] args) {
// Return 6 unique numbers between 1 and 40
System.out.println(NRand.nUniqueRandom(6, 1, 40));
}
/**
* Produce a Set of 'howMany' random integers in the range
* between 'lowerBound' and 'upperBound' inclusive
*
* @param howMany How many numbers do we want?
* @param lowerBound The lower bound of the range (inclusive)
* @param upperBound The upper bound of the range (inclusive)
*
* @return A Set containing integers
*/
public static Set<Integer> nUniqueRandom(int howMany, int lowerBound,
int upperBound) {
Set<Integer> numbers = new HashSet<Integer>(howMany);
while (numbers.size() < howMany) {
numbers.add((int) (Math.random() * (upperBound - lowerBound + 1)) +
lowerBound);
}
return numbers;
}
}
import java.util.Set;
public class NRand {
/**
* For testing
*/
public static void main(String[] args) {
// Return 6 unique numbers between 1 and 40
System.out.println(NRand.nUniqueRandom(6, 1, 40));
}
/**
* Produce a Set of 'howMany' random integers in the range
* between 'lowerBound' and 'upperBound' inclusive
*
* @param howMany How many numbers do we want?
* @param lowerBound The lower bound of the range (inclusive)
* @param upperBound The upper bound of the range (inclusive)
*
* @return A Set containing integers
*/
public static Set<Integer> nUniqueRandom(int howMany, int lowerBound,
int upperBound) {
Set<Integer> numbers = new HashSet<Integer>(howMany);
while (numbers.size() < howMany) {
numbers.add((int) (Math.random() * (upperBound - lowerBound + 1)) +
lowerBound);
}
return numbers;
}
}
import java.util.*;
public class Rand {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<Integer>();
Random ran = new Random();
for(int i = 1; i <= 30; i++)
al.add(i);
for(int i = 0; i < 3; i++) {
int num = al.remove(ran.nextInt(al.size()));
System.out.println("Num is: " + num);
}
}
}
public class Rand {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<Integer>();
Random ran = new Random();
for(int i = 1; i <= 30; i++)
al.add(i);
for(int i = 0; i < 3; i++) {
int num = al.remove(ran.nextInt(al.size()));
System.out.println("Num is: " + num);
}
}
}