- Getting random numbers in Java [duplicate]
- 2 Answers 2
- 1. Using Math.random()
- 2. Using Random class in Java.
- Class Random
- Generating Random Numbers in a Range in Java
- 1. Overview
- Further reading:
- Generating Random Numbers in Java
- Java — Random Long, Float, Integer and Double
- Java — Generate Random String
- 2. Generating Random Numbers in a Range
- 2.1. Math.random
- 2.2. java.util.Random.nextInt
- 2.3. java.util.Random.ints
- 3. Generating Random Numbers in a Range With Some Exclusions
- 3.1. Math.random()
- 3.2. java.util.Random.nextInt()
- 3.3. java.util.Random.ints()
- 4. Conclusion
Getting random numbers in Java [duplicate]
I would like to get a random value between 1 to 50 in Java. How may I do that with the help of Math.random(); ? How do I bound the values that Math.random() returns?
2 Answers 2
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;
int random = (int)(Math.random() * 50 + 1);
So if I take 45 as a minimum and rand.nextInt(50) returns 30, I get a value between 45 and 50? Uhm. ok.
@DanielF ‘s confusion is understandable because the comment in the answer is misleading. The 50 in rand.nextInt(50) will only give the maximum in this situation. rand.nextInt(50) will return an integer between 0 (inclusively) and 50 (exclusively) (in other words 21). We add 1 to have 43. So, if you take 45 as a minimum and add it to rand.nextInt(50), you’ll have a value between 45 and 94 inclusively.
1. Using Math.random()
double random = Math.random() * 49 + 1; or int random = (int )(Math.random() * 50 + 1);
This will give you value from 1 to 50 in case of int or 1.0 (inclusive) to 50.0 (exclusive) in case of double
Why?
random() method returns a random number between 0.0 and 0.9. you multiply it by 50, so upper limit becomes 0.0 to 49.999. when you add 1, it becomes 1.0 to 50.999. now when you truncate to int, you get 1 to 50. (thanks to @rup in comments). leepoint’s awesome write-up on both the approaches.
2. Using Random class in Java.
Random rand = new Random(); int value = rand.nextInt(50);
This will give value from 0 to 49.
For 1 to 50: rand.nextInt((max — min) + 1) + min;
Source of some Java Random awesomeness.
Class Random
An instance of this class is used to generate a stream of pseudorandom numbers; its period is only 2 48 . The class uses a 48-bit seed, which is modified using a linear congruential formula. (See Donald E. Knuth, The Art of Computer Programming, Volume 2, Third edition: Seminumerical Algorithms , Section 3.2.1.)
If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random . Java implementations must use all the algorithms shown here for the class Random , for the sake of absolute portability of Java code. However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods.
The algorithms implemented by class Random use a protected utility method that on each invocation can supply up to 32 pseudorandomly generated bits.
Many applications will find the method Math.random() simpler to use.
Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom in multithreaded designs.
Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.
Generating Random Numbers in a Range in Java
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We’re looking for a new Java technical editor to help review new articles for the site.
1. Overview
In this tutorial, we’ll explore different ways of generating random numbers within a range.
Further reading:
Generating Random Numbers in Java
Java — Random Long, Float, Integer and Double
Java — Generate Random String
2. Generating Random Numbers in a Range
2.1. Math.random
Math.random gives a random double value that is greater than or equal to 0.0 and less than 1.0.
Let’s use the Math.random method to generate a random number in a given range [min, max):
public int getRandomNumber(int min, int max)
Why does that work? Let’s look at what happens when Math.random returns 0.0, which is the lowest possible output:
So, the lowest number we can get is min.
Since 1.0 is the exclusive upper bound of Math.random, this is what we get:
1.0 * (max - min) + min => max - min + min => max
Therefore, the exclusive upper bound of our method’s return is max.
In the next section, we’ll see this same pattern repeated with Random#nextInt.
2.2. java.util.Random.nextInt
We can also use an instance of java.util.Random to do the same.
Let’s make use of the java.util.Random.nextInt method to get a random number:
public int getRandomNumberUsingNextInt(int min, int max)
The min parameter (the origin) is inclusive, whereas the upper bound max is exclusive.
2.3. java.util.Random.ints
The java.util.Random.ints method returns an IntStream of random integers.
So, we can utilize the java.util.Random.ints method and return a random number:
public int getRandomNumberUsingInts(int min, int max)
Here as well, the specified origin min is inclusive, and max is exclusive.
3. Generating Random Numbers in a Range With Some Exclusions
We can also generate a random number within a specified range while excluding certain values.
3.1. Math.random()
Let’s use Math.random() to generate a random number within a specified range while excluding some values:
static int getRandomWithExclusionUsingMathRandom(int min, int max, int [] exclude) < Arrays.sort(exclude); int random = min + (int) ((max - min + 1 - exclude.length) * Math.random()); for (int ex : exclude) < if (random < ex) < break; >random++; > return random; >
In the code above, we add an array of integers to the method argument. The exclude array contains integer values that should be excluded from the random number generation.
Furthermore, we sort the array in ascending order to optimize the loop. By sorting the array, we ensure that once we’ve found an excluded number greater than the random number, we won’t find any more and break the loop early. If the array isn’t sorted, the loop might break prematurely.
Let’s take a moment to understand how the algorithm works to ensure that incremented random value isn’t in the exclude array. We can assume we have an array containing values we’re excluding and a random number:
int[] exclude = ; int random = 3;
Next, let’s iterate through the array and compare it with the random number:
for (int ex : exclude) < if (random < ex) < break; >random++; > return random;
Firstly, the algorithm begins by comparing the random value with the first element in the exclude array. Since the random value isn’t less than the first element in the array, the loop continues and increments the random number to 4.
Next, the loop then moves to the next element, which is 3. As the random number isn’t less than 3, the loop continues, incrementing the random number to 5.
Furthermore, the next value in the array is 5, which is equal to the random number. The loop increments the random number to 6 and then stops as we’ve reached the end of the array. Therefore, the returned random number is 6.
Notably, if the random value is less than any element in the array, the loop will break and return the current random value.
In the next section, we’ll use java.util.Random.nextInt() method to generate a random number within a specified range while excluding certain values, applying the same algorithm.
3.2. java.util.Random.nextInt()
In a previous section, we saw how to use java.util.Random.nextInt() to generate a random number within a specified range. Let’s broaden the method by implementing the functionality to exclude some numbers:
static int getRandomNumberWithExclusionUsingNextInt(int min, int max, int [] exclude) < Random rnd = new Random(); Arrays.sort(exclude); int random = min + rnd.nextInt(max - min + 1 - exclude.length); for (int ex : exclude) < if (random < ex) < break; >random++; > return random; >
Here, we create a new instance of Random and invoke the nextInt() method on it to generate a random number within a specific range with some exclusions.
3.3. java.util.Random.ints()
We can also generate a random number while excluding some values using the java.util.Random.ints() method:
int getRandomWithExclusion(int min, int max, int [] exclude) < Random rnd = new Random(); OptionalInt random = rnd.ints(min, max + 1) .filter(num ->Arrays.stream(exclude).noneMatch(ex -> num == ex)) .findFirst(); return random.orElse(start); >
The code above generates a stream of random integers within the specified range. We then use the filter() method of the Stream API to eliminate numbers in the exclude array.
Finally, we use the findFirst() method to get a number in the stream that’s not in the exclude array.
4. Conclusion
In this article, we saw alternative ways of generating random numbers within a range.
Code snippets, as always, can be found over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes: