Since you (hopefully) can't predict random numbers in Java, we'll need to store the numbers that we've generated so far. A Set seem ideal for this, as it automatically handles keeping itself free of duplicates. The problem is that the order in which elements are removed from a set are not guaranteed to be in the same as the order in which they were added. I would suggest using a List of some sort:
// returns a List of n random integers from 0 to max
static List<Integer> getUniqueRandomInts(final int n, final int max) {
// if n > max, this function would never return, so remove the possibility
if (n > max) {
return null;
}
// new list of values
final List<Integer> list = new ArrayList<Integer>();
// seed our random generator with the current time
final Random rnd = new Random(System.currentTimeMillis());
// keep trying to add numbers until we have the proper number
while (list.size() < n) {
int num = rnd.nextInt(max);
if (!list.contains(num)) {
list.add(num);
}
}
return list;
}
Chat with our AI personalities
Random numbers cannot be generated programatically. For pseudo-random numbers use function 'rand'.
yes, because the number generated is from the computer's CPU database and is selected randomly therefore it must be a random number It depends on how the numbers are generated. If they are based on things in the environment, like noise levels, then yes. If they are solely generated by computer functions, then no, they are pseudo-random numbers, which will be random enough for most purposes.
In computing, a hardware random number generator is an apparatus that generates random numbers from a physical process.
Take advantage of Java's easy-to-use Random class.// Create a new Random object.// The constructor accepts a single Long argument.// This is the seed for the random generator.// Using the current time is standard for most applications.Random rnd = new Random(System.currentTimeMillis());// A call to nextInt(n) will generate a random value from 0 to n-1// This is typical in programming languages, and in order to get a specific range we need// to tweak it a bit.rnd.nextInt(n);// This will give you a random int from (start) to (start + range - 1)rnd.nextInt(range) + start;
this is the code for making a random number using python: import random >>>random.randint (1, 10) you can do whatever numbers you want.