🌐
Stack Overflow
stackoverflow.com › questions › 70227878 › how-do-i-generate-random-numbers-then-add-to-a-set-in-java
how do I generate random numbers then add to a set in Java? - Stack Overflow

You need to add the element inside the loop, to do it 10 times

Random coins = new Random();
HashSet<Integer> hash = new HashSet<>();
for (int count = 1; count <= 10; count++) {
    hash.add(1 + coins.nextInt(100));
}
System.out.println(hash); // [50, 23, 72, 9, 89, 10, 76, 13, 47]

Note that is a number is generated twice, you'll end up with 9 values as Set doesn't allow duplicate, to ensure a 10 item set, use a while loop

while (hash.size() != 10) {
    hash.add(1 + coins.nextInt(100));
}
Answer from azro on stackoverflow.com
🌐
Stack Overflow
stackoverflow.com › questions › 25660804 › how-can-i-generate-a-random-number-of-any-particular-number-of-digits-say-5-in
how can I generate a random number of any particular number of digits (say 5) in java? - Stack Overflow

Create a random integer in range 0,10^k - 10^(k-1), and add 10^(k-1) - in your example. range 0,90000, and add 10000 to it.

Use the Random.nextInt(int) method for it.

Something like:

new Random().nextInt(90000) + 10000
Answer from amit on stackoverflow.com
🌐
Stack Overflow
stackoverflow.com › questions › 8920353 › how-do-i-create-an-array-with-1000-randomly-generated-ints
java - How do I create an array with 1000 randomly generated ints? - Stack Overflow

Eyeballing it, your findLargest method looks good -- it is using the correct approach.

To generate the list of 1000 numbers, you need to initialize the array to 1000 elements. Right now you are initializing it to have a random number of elements, which is not what you want. After you initialize the numbers to be an int[] of length 1000, you need to loop over the array putting a random number in. Some something like

int [] numbers = new int[1000]; // generate a new int[]

for (i = 0; i < number.length; i++) {
  numbers[i] = xxxx; // generate a random number
}

You should probably create some sort of init method that creates the original array for you. You would invoke it in main, get the reference to the array, then pass that array to your find method, then print the result.

You are almost there.

Answer from hvgotcodes on stackoverflow.com
🌐
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

Java 7+

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.

Java 17+

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.

Earlier Java

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
🌐
Stack Overflow
stackoverflow.com › questions › 22612684 › generate-10-000-random-values-in-a-table
sql - Generate 10,000 random values in a table - Stack Overflow

If you are looking for just something chaotic in CLOB (including length and content) you may use DBMS_RANDOM:

SQL> select DBMS_RANDOM.STRING('p',DBMS_RANDOM.VALUE(1,30)) rand_str from dual connect by level <= 10
  2  /

RAND_STR                                                                        
--------------------------------------------------------------------------------
#<a                                                                             
tV&Og8=:f}Is/sR2L>F\7wCL)_V2                                                    
/WBp Y)V5ZD.v                                                                   
_yw(o_                                                                          
b:5&E}7\a1Gt]X}$}e*-W[6U=1                                                      
L<hQ:L^5}A(]<:}+8|-{.F%&`L                                                      
G!L'Rbgiw/o]r~`[@9d6FUi3dc7                                                     
.h_y;yeh`*rUK+\~8^i<G+;L76*                                                     
ec}aL                                                                           
d3)UFT)S2kDA5    

And the same package can be used to generate values in other columns (but I suppose ERRORID is a primary key, so you can use any other method which guarantess uniqueness - like sequence).

SQL> create sequence seq_x;

SQL> select x_seq.nextval, DBMS_RANDOM.STRING('p',DBMS_RANDOM.VALUE(1,30)) rand_str,
systimestamp + numtodsinterval(DBMS_RANDOM.VALUE(1,40),'MINUTE') rand_ts 
from dual connect by level <= 10;

   NEXTVAL RAND_STR                        RAND_TS                               
---------- ------------------------------  -----------------------------------   
         1 a?=PK7yA|L8]d/)3!               24.03.14 19:47:18,750326032 +04:00    
         2 $N+K4vksVx(npxm^'#/%.Aay5$,     24.03.14 19:50:48,361699672 +04:00    
         3  },7(1iX,2'E@i3u;wdg?.BB        24.03.14 19:35:15,711777571 +04:00    
         4 :S8x vj!m!:YI% fLCy8$\Y_}C      24.03.14 19:43:41,088255060 +04:00    
         5 /'oFj@+jOv3uFZC\z;^2+9GG~       24.03.14 19:59:02,214021766 +04:00    
         6 8vTh0}[HYBEDy{4\                24.03.14 20:06:34,600594460 +04:00    
         37 >u w9q)]c7/hB_butzNR\Oi!hWwO<& 24.03.14 19:36:39,010531153 +04:00    
         8 >GwzDBT8!?g}(<8;@I              24.03.14 19:51:52,118620451 +04:00    
         9 -] 'NxHUx46"_(df"8.u:6Pel"      24.03.14 19:44:04,152845952 +04:00    
        10 "HAJ                            24.03.14 20:00:24,933479299 +04:00    
Answer from Dmitry Nikiforov on stackoverflow.com
🌐
Stack Overflow
stackoverflow.com › questions › 12458383 › java-random-numbers-using-a-seed
Java random numbers using a seed - Stack Overflow

If you're giving the same seed, that's normal. That's an important feature allowing tests.

Check this to understand pseudo random generation and seeds:

Pseudorandom number generator

A pseudorandom number generator (PRNG), also known as a deterministic random bit generator DRBG, is an algorithm for generating a sequence of numbers that approximates the properties of random numbers. The sequence is not truly random in that it is completely determined by a relatively small set of initial values, called the PRNG's state, which includes a truly random seed.

If you want to have different sequences (the usual case when not tuning or debugging the algorithm), you should call the zero argument constructor which uses the nanoTime to try to get a different seed every time. This Random instance should of course be kept outside of your method.

Your code should probably be like this:

private Random generator = new Random();
double randomGenerator() {
    return generator.nextDouble()*0.5;
}
Answer from Denys Séguret on stackoverflow.com
🌐
Oracle
docs.oracle.com › javase › tutorial › collections › interfaces › set.html
The Set Interface - Java Tutorials
This collections Java tutorial describes interfaces, implementations, and algorithms in the Java Collections framework
🌐
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
🌐
Simplilearn
simplilearn.com › home › resources › software development › set in java: the methods and operations you can perform
Set in Java: The Methods and Operations You Can Perform
July 16, 2024 - The set in Java is an interface available in the java.util package. In this article, you will learn everything about set, its operations, methods and more.
Address: 201 Spear Street, Suite 1100, San Francisco, CA 94105 United States
🌐
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
🌐
upGrad
upgrad.com › tutorials › software-engineering › java-tutorial › set-in-java
Set in Java: A Comprehensive Guide | upGrad
July 31, 2024 - Learn how to create, manipulate, and optimize sets in your Java applications. Master the intricacies of data structures and discover powerful techniques for managing collections in Java
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 – generate random number in range
Java 8 - Generate Random Number in Range
September 6, 2023 - Learn to generate random numbers (ints, floats) in a range using new methods added in Java 8 in Random, SecureRandom and ThreadLocalRandom.
🌐
Softwaretestinghelp
softwaretestinghelp.com › set interface in java: java set tutorial with examples
Set Interface In Java: Java Set Tutorial With Examples
March 7, 2024 - This Java Set Tutorial Explains All about the Set Interface in Java. It covers how to Iterate through a Set, Set Methods, Implementation, Set to List etc.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Set
Set - JavaScript | MDN
The Set object lets you store unique values of any type, whether primitive values or object references.
🌐
Dirask
dirask.com › posts › Java-generate-set-with-10-random-unique-numbers-k1wX7D
Java - generate set with 10 random unique numbers
Generate set with 10 random unique numbers in Java. Code flow: Set random numbers minVal = 50 and maxVal = 100 Until set size is not 10 add new random int - so ...
🌐
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 Exchange
dba.stackexchange.com › questions › 189599 › how-to-insert-10000-new-rows
postgresql - How to insert 10000 new rows? - Database Administrators Stack Exchange

You can use the generate_series() set returning function:

INSERT INTO bins (id) 
SELECT g.id
FROM generate_series(1, 10000) AS g (id) ;
Answer from ypercubeᵀᴹ on dba.stackexchange.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
🌐
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