You can come very close using the code you already have, by just adding the modulo operator for the second and third lists. Adding elements "mod 1000" ensures that you have no values in the list greater than 1000. (You have to add one to the resulting values to shift the range up from 0-999 to 1-1000).

inputTenThousand2[a] = (a % 1000) + 1;

Of course, this doesn't preserve the sorted order you created originally, but once you generate these arrays, you'll notice a very clear pattern. Your array is now just the numbers 1-1000, repeated ten times. This makes picturing what the array would look like sorted very easy:

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
 ...
 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000] 

So, we can just construct that nice sorted list in the first place:

int [] inputTenThousand2 = new int[10000];     // 10000 sorted integers
for (int v = 0; v < 1000; v++) { // loop from 0 to 999
    for (int i = 0; i < 10; i++) { 
        inputTenThousand2[(10*v) + i] = v + 1; // Set ten elements per value of the outer loop
    }
}

You can then copy this list into a third list and "slightly unsort" it for your third case!


Of course, depending on what you have access to (this looks like an assignment, so maybe you don't have sorting readily available), it's likely to be easier to just create the first list as you have it already, then copy it and sort it for the second case.

Answer from Henry Keiter on Stack Overflow
🌐
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

You can come very close using the code you already have, by just adding the modulo operator for the second and third lists. Adding elements "mod 1000" ensures that you have no values in the list greater than 1000. (You have to add one to the resulting values to shift the range up from 0-999 to 1-1000).

inputTenThousand2[a] = (a % 1000) + 1;

Of course, this doesn't preserve the sorted order you created originally, but once you generate these arrays, you'll notice a very clear pattern. Your array is now just the numbers 1-1000, repeated ten times. This makes picturing what the array would look like sorted very easy:

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
 ...
 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000] 

So, we can just construct that nice sorted list in the first place:

int [] inputTenThousand2 = new int[10000];     // 10000 sorted integers
for (int v = 0; v < 1000; v++) { // loop from 0 to 999
    for (int i = 0; i < 10; i++) { 
        inputTenThousand2[(10*v) + i] = v + 1; // Set ten elements per value of the outer loop
    }
}

You can then copy this list into a third list and "slightly unsort" it for your third case!


Of course, depending on what you have access to (this looks like an assignment, so maybe you don't have sorting readily available), it's likely to be easier to just create the first list as you have it already, then copy it and sort it for the second case.

Answer from Henry Keiter on stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › set-in-java
Set in Java - GeeksforGeeks
July 2, 2024 - 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.
🌐
Coderanch
coderanch.com › t › 620333 › java › random-numbers-users-choosen-number
10,000 random numbers between 1 and the users choosen number (Beginning Java forum at Coderanch)
I need an actionPerformed method that will take the number the user enters in the JTextField and generate 10,000 random numbers between 1 and the users number then output min max and mean of the random numbers. Here is what I have so far which isn't much.
🌐
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 ...
🌐
Digitalocean
digitalocean.com › community › tutorials › java-set
Java Set – Set in Java | DigitalOcean
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 › 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
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.
🌐
Codejava
codejava.net › java-core › collections › initialize-set-with-values
Java Initialize Set with Values in One Line
Java code examples to create a Set that is initialized with some elements in just a single line.
🌐
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 \$O(n^2)\$ algorithm to \$O(n)\$).

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
🌐
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.
🌐
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
🌐
Baeldung
baeldung.com › home
Initializing HashSet at the Time of Construction | Baeldung
3 weeks ago - Explore multiple ways to initialize a HashSet while it's constructed.
🌐
Stack Overflow
stackoverflow.com › questions › 20389890 › generating-a-random-number-between-1-and-10-java
Generating a Random Number between 1 and 10 Java - Stack Overflow

As the documentation says, this method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)". This means that you will get numbers from 0 to 9 in your case. So you've done everything correctly by adding one to that number.

Generally speaking, if you need to generate numbers from min to max (including both), you write

random.nextInt(max - min + 1) + min
Answer from Malcolm on stackoverflow.com
🌐
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 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
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › generating-random-numbers-in-java
Generating random numbers in Java - GeeksforGeeks
February 28, 2023 - 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.
🌐
Jenkov
jenkov.com › tutorials › java-collections › set.html
Java Set
The Java Set interface represents a collection of objects where each element in the Java Set is unique. In other words, the same element cannot occur multiple times in a Java Set. This Java Set tutorial explains how the Java Set interface and its implementations work.
🌐
Stack Overflow
stackoverflow.com › questions › 9470316 › creating-prepopulated-set-in-java
initialization - Creating prepopulated set in Java - Stack Overflow

Try this idiom:

import java.util.Arrays;

new HashSet<Integer>(Arrays.asList(1, 2, 3, 6))
Answer from Tomasz Nurkiewicz on stackoverflow.com
🌐
HowToDoInJava
howtodoinjava.com › home › generating random numbers in java
Generating Random Numbers in Java (with Thread Safety)
September 6, 2023 - However, the values collectively ... if these values were generated by a single thread. Instances of SplittableRandom are not thread-safe. They are designed to be split, not shared, across threads. SplittableRandom random = new SplittableRandom(); SplittableRandom splitted = random.split(); random.nextInt(10000)); //Thread 1 splitted.nextInt(10000)); //Thread 2 · Java 7 introduced ...