With Java 8 it is so simple so it doesn't even need separate method anymore:

List<Integer> range = IntStream.rangeClosed(start, end)
    .boxed().collect(Collectors.toList());

And in Java 16 or later:

List<Integer> range = IntStream.rangeClosed(start, end)
    .boxed().toList();
Answer from Vladimir Matveev on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › set-in-java
Set in Java - GeeksforGeeks
19:34
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.
Published: February 4, 2016
🌐
Stack Overflow
stackoverflow.com › questions › 22797177 › how-would-you-make-an-array-of-10000-with-only-values-of-1-1000-inclusive
java - How would you make an array of 10000 with only values of 1-1000 inclusive? - Stack Overflow
Any help will be appreciated!! int [] inputTenThousand = new int[10000]; // Random 10000 for (int a = 0; a < inputTenThousand.length; a++) { inputTenThousand [a] = (int) (Math.random () * 1000); } int [] inputTenThousand2 = new int[10000] // Sorted 10000 for (int a = 0; a < inputTenThousan...
🌐
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...
🌐
Stack Overflow
stackoverflow.com › questions › 10242380 › how-can-i-generate-a-list-or-array-of-sequential-integers-in-java
How can I generate a list or array of sequential integers in Java? - Stack Overflow

With Java 8 it is so simple so it doesn't even need separate method anymore:

List<Integer> range = IntStream.rangeClosed(start, end)
    .boxed().collect(Collectors.toList());

And in Java 16 or later:

List<Integer> range = IntStream.rangeClosed(start, end)
    .boxed().toList();
Answer from Vladimir Matveev on stackoverflow.com
🌐
Stack Exchange
codereview.stackexchange.com › questions › 156191 › generate-random-and-unique-array-of-int-values-for-a-given-size
java - Generate random and unique array of int values for a given size - Code Review Stack Exchange

While your code looks right, there are two concerns I have with it.

The first is the somewhat arbitrary use of desiredSize * 3 as the limit of the random numbers. Why that value?

The performance issue you have is the nested looping you have first to generate the values, and then inside you loop again to check for duplicates. You can reduce the inner loop significantly by using a Set in combination with the array to check for uniqueness. The set will consume more memory, but it will allow a check without any looping (it will reduce your \ algorithm to \).

The code would look something like:

public static int[] generateRandAndUniqSet(int desiredSize) {
    int[] arrayResult = new int[desiredSize];
    Set<Integer> uniq = new HashSet<>();
    Random rand = new Random();
    int counter = 0;
    while (counter < desiredSize) {
        int randValue = rand.nextInt(desiredSize*3);/* a larger interval! */
        if (uniq.add(randValue)) {
            arrayResult[counter++] = randValue;
        }
    }
    return arrayResult;
}    

That Set change will have a significant impact on your performance.... but, is there a better way?

Assuming your limit of desiredSize * 3 and assuming a relatively small dataset (less than a million, or so), then a better option would be for you to:

  1. create an array of size desiredSize * 3
  2. populate it with consecutive numbers [0, 1, 2, 3, 4, ....., desiredsize * 3 - 1]
  3. shuffle it using a Fisher-Yates shuffle.
  4. return the first desiredSize elements from the shuffled array.

This would require no duplicate-checking at all.

I put together some code to demonstrate this:

public static final int[] generateRandAndUniqRGL(int desiredSize) {

    // generate set of sequential values from 0 ... desiredSize * 3
    int[] set = IntStream.range(0,  desiredSize * 3).toArray();

    // shuffle them
    int index = set.length;
    // Fisher-Yates.
    Random rand = new Random();
    while (index > 1) {
        final int pos = rand.nextInt(index--);
        final int tmp = set[pos];
        set[pos] = set[index];
        set[index] = tmp;
    }

    // return the first batch of them
    return Arrays.copyOf(set, desiredSize);
}

I timed this method against yours for a few sizes of data here in ideone: https://ideone.com/MrwWLV

Note the timing results:

OP function for 10 input took  0.012ms
RL function for 10 input took  0.016ms
OP function for 100 input took  0.054ms
RL function for 100 input took  0.032ms
OP function for 1000 input took  3.896ms
RL function for 1000 input took  0.603ms
OP function for 10000 input took 164.937ms
RL function for 10000 input took  1.750ms
Answer from rolfl on codereview.stackexchange.com
🌐
GeeksforGeeks
geeksforgeeks.org › generating-random-numbers-in-java
Generating random numbers in Java - GeeksforGeeks
October 26, 2016 - 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.
🌐
Stack Overflow
stackoverflow.com › questions › 38465148 › best-data-structure-to-store-10-000-records-in-java
algorithm - Best data structure to store 10,000 records in java - Stack Overflow

The HashSet provides both O(1) insertion and O(1) search, which is hard to top from a theoretical point of view.

In practice, for a size of 10.000 references, a sorted ArrayList might still outperform HashSet, although insertion is O(n) and search is O(log(n)). Why? Because it stores the data (the references at least) in a contiguous memory range and therefore can take advantage of hardware memory caching.

The issue with big-O notation is that it completely ignores the time required for a single operation. That's fine for asymptotic considerations and very huge data sets, but for a size of 10.000 it might be misleading.

Haven't tried it, though. And I bet your Interviewer hasn't either :).

Answer from Frank Puffer on stackoverflow.com
🌐
Digitalocean
digitalocean.com › community › tutorials › random-number-generator-java
Random Number Generator in Java | DigitalOcean
August 3, 2022 - Technical tutorials, Q&A, events — This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.
🌐
Stack Overflow
stackoverflow.com › questions › 5271598 › java-generate-random-number-between-two-given-values
Java Generate Random Number Between Two Given Values - Stack Overflow

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)

Answer from Erik on stackoverflow.com
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 363681 › how-do-i-generate-random-integers-within-a-specific-range-in-java
How do I generate random integers within a specific range in Java? - Stack Overflow

In Java 1.7 or later, the standard way to do this (generate a basic non-cryptographically secure random integer in the range [min, max]) is as follows:

import java.util.concurrent.ThreadLocalRandom;

// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);

See the relevant JavaDoc. This approach has the advantage of not needing to explicitly initialize a java.util.Random instance, which can be a source of confusion and error if used inappropriately.

However, conversely with ThreadLocalRandom there is no way to explicitly set the seed so it can be difficult to reproduce results in situations where that is useful such as testing or saving game states or similar.

As of Java 17, the psuedorandom number generating classes in the standard library implement the RandomGenerator interface. See the linked JavaDoc for more information. For example, if a cryptographically strong random number generator is desired, the SecureRandom class can be used.

Before Java 1.7, the standard way to do this is as follows:

import java.util.Random;

/**
 * Returns a pseudo-random number between min and max, inclusive.
 * The difference between min and max can be at most
 * <code>Integer.MAX_VALUE - 1</code>.
 *
 * @param min Minimum value
 * @param max Maximum value.  Must be greater than min.
 * @return Integer between min and max, inclusive.
 * @see java.util.Random#nextInt(int)
 */
public static int randInt(int min, int max) {

    // NOTE: This will (intentionally) not run as written so that folks
    // copy-pasting have to think about how to initialize their
    // Random instance.  Initialization of the Random instance is outside
    // the main scope of the question, but some decent options are to have
    // a field that is initialized once and then re-used as needed or to
    // use ThreadLocalRandom (if using at least Java 1.7).
    // 
    // In particular, do NOT do 'Random rand = new Random()' here or you
    // will get not very good / not very random results.
    Random rand;

    // nextInt is normally exclusive of the top value,
    // so add 1 to make it inclusive
    int randomNum = rand.nextInt((max - min) + 1) + min;

    return randomNum;
}

See the relevant JavaDoc. In practice, the java.util.Random class is often preferable to java.lang.Math.random().

In particular, there is no need to reinvent the random integer generation wheel when there is a straightforward API within the standard library to accomplish the task.

Answer from Greg Case on stackoverflow.com
🌐
Java67
java67.com › 2015 › 01 › how-to-get-random-number-between-0-and-1-java.html
How to Generate Random Number between 1 to 10 - Java Example | Java67
In the second snippet there's ... (1000, 10000). But hey, that's nice post anyway. :)ReplyDelete ... Load more... Feel free to comment, ask questions if you have any doubt. ... How to remove all elements of ArrayList in Java - ... ... How to declare ArrayList with values in ...
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › › › java › util › Set.html
Set (Java Platform SE 8 )
The Set interface places additional stipulations, beyond those inherited from the Collection interface, on the contracts of all constructors and on the contracts of the add, equals and hashCode methods. Declarations for other inherited methods are also included here for convenience.
🌐
Baeldung
baeldung.com › home
Initializing HashSet at the Time of Construction | Baeldung
July 22, 2018 - Explore multiple ways to initialize a HashSet while it's constructed.
🌐
www.javatpoint.com
javatpoint.com › set-in-java
Set in Java - Javatpoint
Set in Java with java tutorial, features, history, variables, object, programs, operators, oops concept, array, string, map, math, methods, examples etc.
🌐
Digitalocean
digitalocean.com › community › tutorials › java-set
Java Set – Set in Java | DigitalOcean
August 3, 2022 - Technical tutorials, Q&A, events — This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.
🌐
Stack Exchange
codereview.stackexchange.com › questions › 25077 › sorting-10-000-unique-randomly-generated-numbers
java - Sorting 10,000 unique randomly-generated numbers - Code Review Stack Exchange

Apart from the compiler errors, implementation issues and code style suggestions others have pointed out, your shuffling algorithm is fundamentally flawed.

Wikipedia explains it nicely:

Similarly, always selecting i from the entire range of valid array indices on every iteration also produces a result which is biased, albeit less obviously so. This can be seen from the fact that doing so yields nn distinct possible sequences of swaps, whereas there are only n! possible permutations of an n-element array. Since nn can never be evenly divisible by n! when n > 2 (as the latter is divisible by n−1, which shares no prime factors with n), some permutations must be produced by more of the nn sequences of swaps than others. As a concrete example of this bias, observe the distribution of possible outcomes of shuffling a three-element array [1, 2, 3]. There are 6 possible permutations of this array (3! = 6), but the algorithm produces 27 possible shuffles (33 = 27). In this case, [1, 2, 3], [3, 1, 2], and [3, 2, 1] each result from 4 of the 27 shuffles, while each of the remaining 3 permutations occurs in 5 of the 27 shuffles.

To demonstrate this bias, I changed your code to only create three elements per array and ran it sixty million times. Here are the results:

Permutation    Occurences 
[1, 2, 3]:     8884128
[2, 3, 1]:     11111352
[3, 1, 2]:     8895318
[3, 2, 1]:     8891062
[2, 1, 3]:     11107744
[1, 3, 2]:     11110396

If your shuffling algorithm were correct, one would expect a relatively uniform distribution. However, the standard deviation is huge at about 1215764 (or ~2%) which should ring alarm bells. For comparison, here are the results of using the proven Fisher–Yates shuffle:

Permutation    Occurences 
[1, 2, 3]:     10000566
[2, 3, 1]:     9998971
[3, 1, 2]:     10000640
[3, 2, 1]:     10000873
[2, 1, 3]:     9998249
[1, 3, 2]:     10000701

As one would expect from a correct implementation, the standard deviation is low at about 1105 (or ~0.002%).

Here's the correct implementation for reference:

for (int i = numbers.length - 1; i > 0; i--)
{
    int swapIndex = random.nextInt(i + 1);
    int temp = numbers[i];
    numbers[i] = numbers[swapIndex];
    numbers[swapIndex] = temp;
}

However, another problem presents itself even with a correct shuffling algorithm:

A pseudo-random number generator is limited by its period, i.e. it can only produce a certain number of unique shuffles:

[...] a shuffle driven by such a generator cannot possibly produce more distinct permutations than the generator has distinct possible states.

java.util.Random has a period no larger than 248 which is unable to produce an overwhelming majority of the 10000! (approximately 2.85 × 1035659) possible permutations of your array. The default implementation of SecureRandom isn't much better at no more than 2160.

In the case of such a long array, the Mersenne Twister is a more adequate choice with a period of 219937-1 and excellently uniform distribution (although still not enough to produce all the possible permutations. At some point, it makes more sense to look into true random number generators that are based on physical phenomena).

So, in my opinion, the real moral of the story is this:

Take special care when working with randomness or pseudorandomness as the consequences of tiny mistakes can be hard to detect but devastating. Use Collections.shuffle instead of reinventing the wheel. For your (presumably) casual use, you might not need to worry about these inadequacies at all. On the other hand, it doesn't hurt to be aware of them.

Answer from Adam on codereview.stackexchange.com
🌐
Stack Overflow
stackoverflow.com › questions › 2041778 › how-to-initialize-hashset-values-by-construction
java - How to initialize HashSet values by construction? - Stack Overflow

There is a shorthand that I use that is not very time efficient, but fits on a single line:

Set<String> h = new HashSet<>(Arrays.asList("a", "b"));

Again, this is not time efficient since you are constructing an array, converting to a list and using that list to create a set.

When initializing static final sets I usually write it like this:

public static final String[] SET_VALUES = new String[] { "a", "b" };
public static final Set<String> MY_SET = new HashSet<>(Arrays.asList(SET_VALUES));

Slightly less ugly and efficiency does not matter for the static initialization.

Answer from Gennadiy on stackoverflow.com
🌐
Stack Overflow
stackoverflow.com › questions › 12756360 › how-to-make-java-set
collections - How to make Java Set? - Stack Overflow

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

Answer from Thomas W on stackoverflow.com