Random number array in java

Java Program to Generate Array of Random Integers

In this tutorial, we will be dealing with how to generate an array of random integers in a given range in Java.

In this tutorial, Emphasis will be on focusing on a random class of java.util package.

If you Don’t Know how to tackle with the above situation, then you are at the right destination because we will be going in-depth on the above-mentioned topic.

Java Program to Generate an Array of Random Integers

Initially, let us discuss the random class of java.util package. Random class is a part of the java. util package.

Therefore, the class provides us with several methods to generate random numbers of type integer, double, etc.

In this tutorial, we will be using the method nextInt() which returns the next integer value.

In contrast, it returns it from the random number generator sequence.

Firstly, we will be likewise creating a class named ‘CheckRandom’.java.Initially, we will be creating a Random class’s instance is created and we will be calling any of its random value generator methods.

Now, we will be creating an integer array.

Meanwhile, after creating an array, now loop till it’s the length,i.e, array’s length and take inputs through nextInt() method and assign accordingly to array one by one.

Now, we will be concluding on the method Array.toString, which returns a string description of a specified array.

Basically, when we use this method, it simply in String converted formatted that is in [a,b,….] format.

Adjacent values or characters are separated by a comma(,), or other special characters.

The above-mentioned Array.toString takes an array as input.

It converts it into a formatted representation to be visible in a string converted format.

Below is Code for the above-mentioned problem:

import java.util.Arrays; import java.util.Random; import java.io.*; public class CheckRandom < public static void main(String[] args) throws IOException < Random r = new Random(); int[] integers = new int[30]; for (int i = 0; i < integers.length; i++) < integers[i] = r.nextInt(); >System.out.println(Arrays.toString(integers)); > >

In Contrast, After completion of the above program, we will be getting an array of random numbers generated in the array listing format that is in string formatted. To Conclude We get our desired result.

Below is the output of the above program:

how to generate an array of random integers in a given range in Java

Источник

How to generate Random Numbers in Java

In this tutorial, we’ll learn how to generate a random number, generate a random array or list, get a random element from an array or list, and shuffle the list elements.

Generate Random Number

Java Random class is having many useful built-in methods for generating random numbers as follows:-

import java.util.Random;  class generateRandom   public static void main( String args[] )   //Creating an object of Random class  Random random = new Random();   //Calling the nextInt() method  System.out.println("A random int: " + random.nextInt());   //Calling the overloaded nextInt() method  System.out.println("A random int from 0 to 49: "+ random.nextInt(50));   //Calling the nextDouble() method  System.out.println("A random double: "+ random.nextDouble());   //Calling the nextFloat() method  System.out.println("A random float: "+ random.nextFloat());   //Calling the nextLong() method  System.out.println("A random long: "+ random.nextLong());  > > 

Generate Random Integer within a specific Range

Let’s create a method that uses Random class to generate a random Integer within the specific range of min and max values inclusive.

public static int generateRandomInt(int min, int max)  return min + new Random().nextInt(max-min+1); > 

The method returns a random integer every time you run it.

System.out.println(generateRandomInt(1, 5)); // Prints random integer "4" // Prints random integer "1" // Prints random integer "5" 

Generate Array of Random Numbers within a specific Range

Let’s create a method that uses Random class and Java Streams to generate an Array of random numbers of a given size and all elements of that Array should be in the given range of min and max values inclusive.

public static int[] generateRandomArray(int size, int min, int max)   return IntStream  .generate(() -> min + new Random().nextInt(max - min + 1))  .limit(size)  .toArray(); > 

Let’s use the above method to generate an Array of 5 random numbers between 0 to 9 inclusive. The method will generate a random array every time you run it.

System.out.println(Arrays.toString(generateRandomArray(5, 0, 9))); // Prints random array "[1, 9, 7, 0, 4]" // Prints random array "[7, 1, 2, 8, 5]" // Prints random array "[5, 7, 5, 2, 3]" 

Generate List of Random Numbers within a specific Range

Let’s create a method using Random class and Java Streams to generate a List of random numbers of a given size and all elements in that List should be in the given range of min and max values inclusive.

public static ListInteger> generateRandomList(int size, int min, int max)   return IntStream  .generate(() -> min + new Random().nextInt(max-min+1))  .limit(size)  .boxed()  .collect(Collectors.toList()); > 

Let’s use the above method to generate a List of 5 random numbers between 0 to 9 inclusive. The method will generate a random list every time you run it.

System.out.println(generateRandomList(5, 0, 9)); // Prints random list "[3, 5, 7, 2, 4]" // Prints random list "[8, 7, 7, 5, 4]" // Prints random list "[5, 9, 8, 7, 5]" 

Get Random Element from an Array

You can get a random element from an Array of elements by generating a random index within the length range of the Array.

Let’s run the below code snippet, which prints the random user from the Array every time:-

String[] users = new String[]  "Adam", "Bill", "Charlie", "David", "Eva", "Fang", "George", "Harry", "Ivy", "Jack" >; Random random = new Random(); System.out.println(users[random.nextInt(users.length)]); // Prints random user "Eva" // Prints random user "Charlie" // Prints random user "Fang" 

Get Random Element from a List

You can get a random element from a List of elements by generating a random index within the size range of the List.

Let’s run the below code snippet, which prints the random user from the list every time:-

ListString> users = List.of("Adam", "Bill", "Charlie", "David", "Eva", "Fang", "George", "Harry", "Ivy", "Jack"); Random random = new Random(); System.out.println(users.get(random.nextInt(users.size()))); // Prints random user "David" // Prints random user "George" // Prints random user "Charlie" 

Shuffle Elements in a List

Java Collections provide a built-in shuffle() method to shuffle the elements of a List.

Let’s shuffle the list of users and return users with the random sequence:-

ListString> userList = List.of("Adam", "Bill", "Charlie", "David", "Eva", "Fang", "George", "Harry", "Ivy", "Jack");  Collections.shuffle(userList); System.out.println(userList); // Prints random list everytime "[Charlie, Bill, Harry, George, Jack, Ivy, Fang, Eva, David, Adam]"  Collections.shuffle(userList); System.out.println(userList); // Prints random list everytime "[Eva, Ivy, Fang, Jack, Harry, Bill, Charlie, George, David, Adam]" 

Let’s return 5 random users from the given list of users:-

Collections.shuffle(userList); ListString> fiveUsers = userList.subList(0, 5); System.out.println(fiveUsers); // Prints "[Eva, Bill, David, George, Fang]" 

See Also

Ashish Lahoti avatar

Ashish Lahoti is a Software Engineer with 12+ years of experience in designing and developing distributed and scalable enterprise applications using modern practices. He is a technology enthusiast and has a passion for coding & blogging.

Источник

How to generate an array of random integers using Stream API Java 8

Scenario
Generation of random values is useful in many fields such as science, cryptography, statistics, simulation etc.
When related to software applications, they are particularly used to test how applications will behave in real environments.
Since user input is highly unpredictable, the applications are tested against random input values which are not supplied by humans but generated randomly by the application itself.

Java 8 streams
There are many ways to generate a random number in java. But there was no direct way of generating an array of random integers.
Java 8 introduced the concept of Streams . It also added some new methods to java.util.Random class which return a stream.
A stream can be utilized to generate an array.
Following are the methods added to java.util.Random class which return a stream of integers :

  1. ints() – Returns an unlimited stream of integers. This stream if directly converted to an array would result in java.lang.OutOfMemoryError .
  2. ints(streamSize) – Returns a stream of specified size. This stream when converted to an array will return an array of size equal to the given stream size.
  3. ints(streamSize, lowerBound, upperBound) – Returns a stream of specified size. This stream when converted to an array will create an array of specified size with integers starting from lower bound value and less than upper bound value.
  4. ints(lowerBound, upperBound) – Same as above except the returned stream is unlimited. This stream if directly converted to an array would result in java.lang.OutOfMemoryError .
Random random = new Random(); int[] array = random.ints(10,25,50).toArray(); for (int i = 0; i  array.length; i++) { System.out.print(array[i]+" "); }

Random random = new Random(); int[] array = random.ints(10,25,50).toArray(); for (int i = 0; i

The above code first initializes an object of class java.util.Random and then calls the three argument method ints() on this object.
First argument to ints() method is the size of the array to be generated,
Second argument is the lower limit of the array, and
Third argument is the upper limit.

Note that the lower limit is inclusive which means that this digit might be included in the elements of the array while the upper limit is exclusive which means that the elements of the array will be at least 1 less than this number.

Output
Following are the outputs of execution of above lines of code 5 times:

32 25 44 40 31 38 44 43 43 43
43 35 43 33 49 28 26 25 25 42
28 38 31 37 40 44 31 39 42 46
43 44 32 46 32 30 31 41 31 42
49 33 49 35 38 49 48 49 43 42

You can see that the elements of the generated array are different in each run.

  1. An error of type java.lang.IllegalArgumentException: bound must be greater than origin is thrown when the lower and upper limit of the method ints(streamSize, lowerBound, upperBound) are same.
  2. If stream size is not supplied to ints() method then a java.lang.OutOfMemoryError is raised.
  3. Similar to ints() method, there are methods such as longs() and doubles()in java.util.Random class which generate a stream for long and double values respectively.
  4. Elements of the generated array might repeat themselves.
  5. If you want to generate a list instead of an array, modify the code slightly as random.ints(10, 25,50).boxed().collect(Collectors.toList()) .
  6. boxed() method of the stream instance returned by the ints() method converts the integer primitives into their wrapper Integer equivalent.


Hit the clap
if the article was useful.

Источник

How do I generate a random array of numbers?

Using java.util.Random class we can create random data such as boolean , integer , floats , double . First you’ll need to create an instance of the Random class. This class has some next***() methods that can randomly create the data.

package org.kodejava.util; import java.util.Arrays; import java.util.Random; public class RandomDemo < public static void main(String[] args) < Random r = new Random(); // generate some random boolean values boolean[] booleans = new boolean[10]; for (int i = 0; i < booleans.length; i++) < booleans[i] = r.nextBoolean(); >System.out.println(Arrays.toString(booleans)); // generate a uniformly distributed int random numbers int[] integers = new int[10]; for (int i = 0; i < integers.length; i++) < integers[i] = r.nextInt(); >System.out.println(Arrays.toString(integers)); // generate a uniformly distributed float random numbers float[] floats = new float[10]; for (int i = 0; i < floats.length; i++) < floats[i] = r.nextFloat(); >System.out.println(Arrays.toString(floats)); // generate a Gaussian normally distributed random numbers double[] doubles = new double[10]; for (int i = 0; i < doubles.length; i++) < doubles[i] = r.nextGaussian(); >System.out.println(Arrays.toString(doubles)); > > 

The result of the code snippet above are:

[true, true, false, true, false, true, true, false, false, true] [34195704, 1462972230, -475641915, -1531017612, 332184915, 1555901473, -276309016, 1433394157, -451221924, -1178823255] [0.3040716, 0.28814012, 0.34028566, 0.021003246, 0.49158317, 0.37954164, 0.5403056, 0.54187375, 0.7157934, 0.5964742] [1.051268591002577, -1.1283332046139989, 0.8351395528722437, -0.24598168031182968, 0.7123515366756693, -0.9661681996105319, -1.6107009669125059, 0.43994917963255387, 1.1309345726165914, 1.2321618489324313] 

For an example to create random number using the Math.random() method see How do I create random number?.

A programmer, recreational runner and diver, live in the island of Bali, Indonesia. Programming in Java, Spring, Hibernate / JPA. You can support me working on this project, buy me a cup of coffee ☕ every little bit helps, thank you 🙏

Источник

Читайте также:  imgExample
Оцените статью