🌐
Educative
educative.io › answers › how-to-generate-random-numbers-in-java
How to generate random numbers in Java
ThreadLocalRandom class in Java provides the mechanism to generate pseudorandom numbers in a safe thread model by providing each thread with its random number generator so that there is no conflict between the threads in the multithreaded environment. Additionally, this class uses an internally generated seed value ...
🌐
Stack Overflow
stackoverflow.com › questions › 22826953 › how-to-create-array-of-100-with-integers-from-1-1000
java - How To create Array Of 100 With Integers From 1-1000? - Stack Overflow

How about this?

int [] array = new int[100];
for (int a = 0; a < array.length; a++) {
    array[a] = (a + 1) * 10;
}

Simple, if you have no other requirement.

Edit: To make it almost sorted (like every 10th unsorted element), there are many ways. One, using BevynQ's solution, can be:

Random r = new Random();
int [] array = new int[100];
for (int a = 0; a < array.length; a++) {
    if ((a + 1) % 10 != 0) {
        array[a] = (a + 1) * 10;
    } else {
        array[a] = r.nextInt(1000);
    }
}
Answer from aa8y on stackoverflow.com
🌐
Atta-Ur-Rehman Shah
attacomsian.com › blog › java-generate-random-numbers
How to generate random numbers in Java
October 8, 2022 - A quick article to learn how to generate random numbers in a range in Java.
🌐
Sentry
sentry.io › sentry answers › java › how do i generate random integers within a specific range in java?
How do I generate random integers within a specific range in Java? | Sentry
The Problem You need to generate random integers within a specific range. Is there a way to do it in Java? The Solution There are a number of ways to generate
🌐
Shiksha
shiksha.com › home › it & software › it & software articles › programming articles › how to generate random numbers in java?
How to Generate Random Numbers in Java? - Shiksha Online
May 11, 2023 - In this article, we will discuss how to generate random numbers in java, using three different methods: random method of math class, random class, and threadrandomclass.
🌐
Quora
quora.com › How-can-we-generate-random-integers-in-Java-using-random-function
How can we generate random integers in Java using random function? - Quora
Answer (1 of 15): There are two principal means of generating random (really pseudo-random) numbers: * the Random class generates random integers, doubles, longs and so on, in various ranges. * the static method Math.randomgenerates doubles between 0 (inclusive) and 1 (exclusive). To generate ...
🌐
Ioflood
ioflood.com › blog › math-random-java
Java Math.random() Function: Number Generation Guide
February 29, 2024 - Are you looking to add a touch of unpredictability to your Java programs? Like a roll of the dice, the Math.random() function in Java can introduce randomness
🌐
Baeldung
baeldung.com › home
Generating Random Numbers in a Range in Java | Baeldung
May 11, 2024 - Learn about alternative ways of generating random numbers within a range in Java.
🌐
Stack Overflow
stackoverflow.com › questions › 153724 › how-to-round-a-number-to-n-decimal-places-in-java
How to round a number to n decimal places in Java - Stack Overflow

Use setRoundingMode, set the RoundingMode explicitly to handle your issue with the half-even round, then use the format pattern for your required output.

Example:

DecimalFormat df = new DecimalFormat("#.####");
df.setRoundingMode(RoundingMode.CEILING);
for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) {
    Double d = n.doubleValue();
    System.out.println(df.format(d));
}

gives the output:

12
123.1235
0.23
0.1
2341234.2125

EDIT: The original answer does not address the accuracy of the double values. That is fine if you don't care much whether it rounds up or down. But if you want accurate rounding, then you need to take the expected accuracy of the values into account. Floating point values have a binary representation internally. That means that a value like 2.7735 does not actually have that exact value internally. It can be slightly larger or slightly smaller. If the internal value is slightly smaller, then it will not round up to 2.7740. To remedy that situation, you need to be aware of the accuracy of the values that you are working with, and add or subtract that value before rounding. For example, when you know that your values are accurate up to 6 digits, then to round half-way values up, add that accuracy to the value:

Double d = n.doubleValue() + 1e-6;

To round down, subtract the accuracy.

Answer from curtisk on stackoverflow.com
🌐
Mkyong
mkyong.com › home › java › java – generate random integers in a range
Java - Generate random integers in a range - Mkyong.com
August 19, 2015 - I took all your ideas and came up with this brief but effective code. Just change the values of 99,1,1 to your min and max to get your #s. If you use 99 as your max, randomly 99 + 1 will make the code generate 100, so if you really want max of 99, use 98 in this code. 😀 · * @author balcopc */ import java...
🌐
Squash
squash.io › home › how to generate random integers in a range in java
How to Generate Random Integers in a Range in Java
November 28, 2023 - A guide on generating random integers within a specific range using Java's Random class.
🌐
Techie Delight
techiedelight.com › home › java › initialize set in java
Initialize Set in Java | Techie Delight
October 9, 2023 - In this post, we will discuss various methods to initialize set in Java. Java is often criticized for its verbosity. For example, creating a set containing
🌐
Dreamincode
dreamincode.net › forums › topic › 294837-java-code-generate-10000-random-integers;-sum-max-min-and-average
Java Code Generate 10000 Random Integers; Sum, Max, Min, And Average - Java | Dream.In.Code
public class RandAnalysis { public ... the i value. You could probably change that to i and in your loop, you could begin from i=1 and i<=10000, so that you get exactly 10000 numbers. Now, coming to your question of largest and smallest, I shall give you the logic of how to go about it. Say, there are 10 numbers. You need to compare the first number with the other ...
🌐
Stack Overflow
stackoverflow.com › questions › 42127539 › adding-random-numbers-1-1000000-in-an-array
java - Adding random numbers 1-1000000 in an array? - Stack Overflow
I have looked up how to add 0-99 to an array. But, my assignment was 1-1000000. I just keep getting really large numbers and no small numbers. Is it just because the chance of getting large numbers...
🌐
Java67
java67.com › 2018 › 01 › 3-ways-to-generate-random-integers-on.html
3 ways to create random numbers in a range in Java - Examples | Java67
Java Programming tutorials and Interview Questions, book and course recommendations from Udemy, Pluralsight, Coursera, edX etc
🌐
Blogger
javarevisited.blogspot.com › 2013 › 05 › how-to-generate-random-numbers-in-java-between-range.html
How to Generate Random Numbers in Java Between Range - Example Tutorial
Thankfully, Random number generation ... 7, along with more popular features like String in Switch and ARM blocks. While random() method seems the most convenient way of generating randoms in Java it only returns random doubles, on the other hand by using Random, you can generate pseudo-random integer, floating-point numbers e.g. double and even random boolean values...
🌐
Tutorialspoint
tutorialspoint.com › java › util › timezone_setseed.htm
java.util.Random.setSeed() Method
The setSeed(long seed) method is used to set the seed of this random number generator using a single long seed · Following is the declaration for java.util.Random.setSeed() method
🌐
Roseindia
roseindia.net › tutorial › java › core › powerset.html
Java generate the powerset of a given set
Java Powerset Function - In this tutorial section we discuss on Java powerset Functions. Learn How to generate powerset of given values. The java Power Set is a set of all the subsets of these sets. Write a java program to generate the powerset of given set. Find syntax or code for powerset, ...
🌐
Stack Exchange
codereview.stackexchange.com › questions › 104419 › returning-an-array-of-integers-with-1000-elements
java - Returning an array of integers with 1000 elements - Code Review Stack Exchange

Your approach is not incorrect. It will get the job done (albeit, slower). If you want to improve your approach, keep reading. But first a few points on your code:

Points on Your code

  1. intArrayHolder seems a bit wordy to me. I believe intArray or even array would serve your purpose, without sacrificing readibility. Same for randomNextInt.
  2. for (int i = 0; i < intArrayHolder.length; i++) is redundant because the length of intArrayHolder will be equal to size owing to the fact that you declared it like so. for (int i = 0; i < size; i++) will serve you better.
  3. Please note that random.nextInt(size + 1) does not return an integer between 1 and 1000. It returns an integer in the range \$[0, 1001)\$, i.e. a number \$x\$ such that \$0\leq x < 1001\$. If you do a count, you will find that you are actually getting \$1001\$ elements. The extra number is \$0\$. To fix it, you must write int randomNextInt = random.nextInt(size) + 1; It is quite easy to understand: you just add a \$1\$ to shift the range from \$[0,1000)\$ to \$[1,1001)\$, i.e. the correct range.
  4. ((!isDuplicate) && (randomNextInt != 0)) can be shortened to !(isDuplicate || ramdomNextInt == 0), by using De Morgan's laws. It would be even better if you flip the condition and force next iteration before adding the element to the array.
  5. A general advice is to update the loop counter only once. People generally estimate the number of times the loop will execute by stealing a glance at the for (... statement. A while loop is preferred when the number of iterations is unknown or updation is irregular.
  6. You seem to be using snake_case along with camelCase. The standard in Java is to use camelCase.

Therefore, the refactored code would be:

import java.util.Random;

public class Domain {

    public int[] randomIntArray(int size) {

        Random random = new Random();
        int array[] = new int[size];

        int i = 0;

        while (i < size) {
            boolean isDuplicate = false;
            int randomInteger = random.nextInt(size) + 1;

            for (int j = 0; j < i; j++) {
                if (array[j] == randomInteger) {
                    isDuplicate = true;
                    break;
                }

            }
            if (isDuplicate) {
                continue;
            } else {
                array[i++] = randomInteger;
            }

        }
        return array;
    }
}

A Better Solution

Your solution's best case running time is \$\Omega(n^2)\$. Moreover, as Boris the Spider pointed out: "... there is absolutely no guarantee that Random.nextInt() won't decide to return 1 for ever and ever. ..." Therefore, it might be possible that your code never terminates (although it will be very unlikely). You can make it faster in the following manner:

import java.util.Random;

public class Domain {

    public int[] randomIntArray(int size) {

        Random random = new Random();
        int array[] = new int[size];
        // populate the array with sequential values
        for (int i = 0; i < size; i++) {
            array[i] = i + 1;
        }
        // "shuffle" the array
        for (int i = 0; i < size; i++) {
            int j = random.nextInt(size - i) + i;
            // swap
            int temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
        return array;
    }
}

It's running time is linear i.e. \$\Theta(n)\$1. I am basically describing the Fisher-Yates shuffle

Some Background Info: The Big-O stuff

The Big-O notation is used to define an upper limit of the number of operations executed (the maximum running time, in simpler terms). For example, if the exact number of iterations based on a given parameter (like the number of elements, digits, etc) called \$n\$ is $$2n^2+3n-4$$ we can say that a reasonable upper limit is \$3n^2\$. In the Big-O notation, the constant term gets absorbed. When we represent this in the Big-O notation, we say: "the (maximum) running time is proportional to \$O(n^2)\$".

People tend to forget the other two notations: the Big-Omega (\$\Omega\$) and the Big-Theta (\$\Theta\$) The former defines a lower limit and the latter is the Big-O and the Big-Omega combined together. In the example above, the lower limit can be \$2n^2\$. Absorbing the constant, we say:"the (minimum) running time is proportional to \$\Omega(n^2)\$". The function can therefore be bounded within both upper and lower limits, or both the upper and the lower limits are in the order of \$\Theta(n^2)\$.

Your code has no upper limit. It only has a lower limit. So, only the \$\Omega\$ is defined for your code (unless we set out to do a lengthy mathematical analysis of the behaviour of the nextInt() function).

I suggest that you read the related Wikipedia articles. (I didn't cover \$o, \omega\$ and \$\theta\$, that's your homework). Remember, Google is your friend!


1 Assuming that the nextInt() method takes \$O(1)\$ (i.e. constant) time to execute.

Answer from Hungry Blue Dev on codereview.stackexchange.com
🌐
GeeksforGeeks
geeksforgeeks.org › initializing-hashset-java
Initializing HashSet in Java - GeeksforGeeks
March 17, 2022 - A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.