Generating a Random Number Between 1 and 10 Java

Generating a Random Number between 1 and 10 Java

As the documentation says, this method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)". This means that you will get numbers from 0 to 9 in your case. So you've done everything correctly by adding one to that number.

Generally speaking, if you need to generate numbers from min to max (including both), you write

random.nextInt(max - min + 1) + min

Java Generate Random Number Between Two Given Values

You could use e.g. r.nextInt(101)

For a more generic "in between two numbers" use:

Random r = new Random();
int low = 10;
int high = 100;
int result = r.nextInt(high-low) + low;

This gives you a random number in between 10 (inclusive) and 100 (exclusive)

Generate two random numbers between 1 to 10 using specific string

Java has random number generator support via the java.util.Random class. This class 'works' by having a seed value, then giving you some random data based on this seed value, which then updates the seed value to something new.

This pragmatically means:

  • 2 instances of j.u.Random with the same seed value will produce the same sequence of values if you invoke the same sequence of calls on it to give you random data.
  • But, seed values are of type long - 64 bits worth of data.
  • Thus, to do what you want, you need to write an algorithm that turns any String into a long.
  • Given that long, you simply make an instance of j.u.Random with that long as seed, using the new Random(seedValue) constructor.

So that just leaves: How do I turn a string into a long?

Easy way

The simplest answer is to invoke hashCode() on them. But, note, hashcodes only have 32 bits of info (they are int, not long), so this doesn't cover all possible seed values. This is unlikely to matter unless you're doing this for crypto purposes. If you ARE, then you need to stop what you are doing and do a lot more research, because it is extremely easy to mess up and have working code that seems to test fine, but which is easy to hack. You don't want that. For starters, you'd want SecureRandom instead, but that's just the tip of the iceberg.

Harder way

Hashing algorithms exist that turn arbitrary data into fixed size hash representations. The hashCode algorithm of string [A] only makes 32-bits worth of hash, and [B] is not cryptographically secure: If you task me to make a string that hashes to a provided value I can trivially do so; a cryptographically secure hash has the property that I can't just cook you up a string that hashes to a desired value.

You can search the web for hashing strings or byte arrays (you can turn a string into one with str.getBytes(StandardCharsets.UTF_8)).

You can 'collapse' a byte array containing a hash into a long also quite easily - just take any 8 bytes in that hash and use them to construct a long. "Turn 8 bytes into a long" also has tons of tutorials if you search the web for it.

I assume the easy way is good enough for this exercise, however.

Thus:

String key = ...;
Random rnd = new Random(key.hashCode());

int number1 = rnd.nextInt(10) + 1;
int number2 = rnd.nextInt(10) + 1;

System.out.println("First number: " + number1);
System.out.println("Second number: " + number2);

Getting random numbers in Java

The first solution is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random():

double random = Math.random() * 49 + 1;

or

int random = (int)(Math.random() * 50 + 1);

random integers between 2 values

If you want a value between two integer values (min and max)
Here you go:

Random r = new Random();
int randInt = r.nextInt(max-min) + min;
System.out.println(randInt);

So max would be 5 and min would be 2 if you want a integer between 2 and 5

Java generating non-repeating random numbers

Integer[] arr = {...};
Collections.shuffle(Arrays.asList(arr));

For example:

public static void main(String[] args) {
Integer[] arr = new Integer[1000];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
Collections.shuffle(Arrays.asList(arr));
System.out.println(Arrays.toString(arr));

}

Generate 100 random UNIQUE Double numbers between 1-10 in java?

As you alluded to in the comments, there's no way to generate 100 unique integers between 1 and 100. Using doubles allows you to do that, but does not guarantee uniqueness by itself (even though there's an infinitesimal chance of getting repeating items), so you would have to guarantee this yourself - e.g., by using a Set:

Set<Double> doubles = new HashSet<>();
while (doubles.size() < 100) {
doubles.add(1 + rand.nextDouble() * 9);
}

EDIT:

JDK 8 provides an arguably more elegant way of achieving this with streams:

List<Double> doubles =
rand.doubles()
.distinct()
.map(d -> 1 + d * 9)
.limit(100)
.boxed()
.collect(Collectors.toList());


Related Topics



Leave a reply



Submit