Random Integer Generation

Random Integer Generation

Question:
How do I write a Java program that generates random numbers withinlimits, such as 1 to 100, or 1 to 1000?

Answer:
The java.util package includes a Random class which will generate asequence of pseudo-random numbers. Pseudo-random number sequencesappear to have a random distribution, but have a definite order.Given the same seed, a pseudo-random number generator will alwaysproduce the same sequence of numbers. Therefore, you shouldinitialize the Random class with as random a seed as possible. Usingthe current time as a seed is often sufficient.

However, when apseudo-random number sequence is exhausted, it wraps around and startsagain from the beginning. Consequently, for long-lived applicationsthat generate many random numbers over time, you will want toperiodically reseed your random generator.

The Random class does not provide a generic means of generating randomintegers within a specific range. Rather, it generates a uniformlydistributed set of values between 0 and some upper bound. For doublesand floats it generates a value between 0 and 1. You can use this togenerate arbitrary ranges of random integers. The following exampleprogram provides a random integer generating class that takes care ofconverting a random double into a random integer within a specificrange. It also takes care of reseeding the random number generatorafter the sequence has been in use for a long time.

import java.util.*;public final class RandomIntGenerator {  public static final int DEFAULT_MIN_RANGE = 1;  public static final int DEFAULT_MAX_RANGE = 100;  int _minRange, _maxRange, _range;  long _numCalls;  Random _random;  public RandomIntGenerator() {    this(DEFAULT_MIN_RANGE, DEFAULT_MAX_RANGE);  }  public RandomIntGenerator(int minRange, int maxRange) {    _random   = new Random(System.currentTimeMillis());    setRange(minRange, maxRange);    _numCalls = 0;  }  public void setRange(int minRange, int maxRange) {    _minRange = minRange;    _maxRange = maxRange;    _range    = maxRange - minRange + 1;  }  public int nextInt() {    double d;    d = ((double)_range)*_random.nextDouble();        if(++_numCalls == Integer.MAX_VALUE) {      // The pseudo-random number sequence is sufficiently      // exhausted that it is time to switch to a new seed.      _numCalls = 0;      _random.setSeed(System.currentTimeMillis());    }    return (_minRange + (int)d);  }  public static final void main(String[] args) {    RandomIntGenerator randomInt;    randomInt = new RandomIntGenerator();    for(int i = RandomIntGenerator.DEFAULT_MIN_RANGE;        i <= RandomIntGenerator.DEFAULT_MAX_RANGE; ++i)      System.out.println(randomInt.nextInt());  }}
Share the Post:
XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes

ransomware cyber attack

Why Is Ransomware Such a Major Threat?

One of the most significant cyber threats faced by modern organizations is a ransomware attack. Ransomware attacks have grown in both sophistication and frequency over the past few years, forcing

data dictionary

Tools You Need to Make a Data Dictionary

Data dictionaries are crucial for organizations of all sizes that deal with large amounts of data. they are centralized repositories of all the data in organizations, including metadata such as