Generate Unique Random Key In Java

  
  • Generate 16-digit unique code (like product serial). I think java UUID is quite unique but it seems to long for the. Generate random and unique array of int.
  • KeyGenerator objects are reusable, i.e., after a key has been generated, the same KeyGenerator object can be re-used to generate further keys. There are two ways to generate a key: in an algorithm-independent manner, and in an algorithm-specific manner.

Dec 18, 2018  This is a very common scenario in programming when there is a requirement to use some unique random id. This tutorial will help us to generate it in Java. In this post, we will see “how to create a unique random ID using the GUID algorithm?” Simplest example of generating a unique random id using GUID algorithm in Java.!!! Click To Tweet. I was actually trying to do Generate a set of unique numbers java to this one (which it is), and forgot to clean this one up. Thank you for reminding me. – user289086 Jan 14 '14 at 15:55 possible duplicate of Generating Unique Random Numbers in Java – Alex Jul 28 '15 at 18:31.

Details
Written by Nam Ha Minh
Last Updated on 04 July 2019 Print Email
In this Java tutorial, you will learn how to generate random numbers using the random() method of the Mathclass and methods of the java.util.Random class.Remember that the generated numbers are actually pseudorandom numbers, or “fake” random numbers. The generated numbers are parts of a very large sequence so they appear to be random, but they are not true random numbers. However, you can use it for cases in which true randomness and security are not required.

1. Generate random numbers using Math.random()

The static method random() of the Math class returns a pseudorandom double value in the range from 0.0 to 1.0. The following code generates a random integer number between 1 and 10 (1 <= x <= 10):And the following code snippet generates 10 random integer numbers between 1 and 10:This code creates an array of 100 random numbers in the range from 1 to 10:Similarly, the following code generates 10 random numbers between 1 and 100:And the following example generates random numbers in the range from 60 to 180:NOTE: The Math.random() method uses the java.util.Random class internally. It calls the nextDouble() method of the Random class that returns a pseudorandom double value between 0.0 and 1.0.


2. Generate random numbers using java.util.Random class

Randomis the base class that provides convenient methods for generating pseudorandom numbers in various formats like integer, double, long, float, boolean and you can even generate an array of random bytes. It is implemented under the

Generate Random Unique Key Java

java.util package so you need to import this class from this package in your code.You can create a new instance of the Random class by using its empty constructor:or by providing a long seed - the initial value of the internal state of the pseudorandom number generator. For example:A random number generator produces pseudorandom numbers in a determinable sequence or pattern, and the seed value specifies the starting point in the sequence, so two Random instances constructed with the same seed will produce the same sequence of pseudorandom numbers.Therefore, you can use the empty constructor in most cases. Use the seed parameter constructor when debugging the code with the same sequence of pseudorandom numbers.The nextBoolean() method returns the next random boolean value, for example:The nextBytes(byte[] bytes)method generates random bytes and put them into the specified byte array, for example:The nextDouble() method returns the next random double value between 0.0 and 1.0. This method is used by the Math.random() method. For example, the code to generate 10 random numbers between 1 and 10 using Random class can be written as follows:The nextFloat() method returns the next random float value between 0.0 and 1.The nextInt() method returns the next random integer value with 2^32 possible int values.The nextInt(int bound) method returns the next random integer value in the range from 0 (inclusive) to the specified bound value (exclusive). So the code to generate 10 random numbers between 1 and 100 can be written using nextInt() method as follows:And the nextLong() method returns the next random long value.


3. Using Java Stream API for random numbers

From Java 8, the Random class provides some methods that return streams of random numbers. For example:This returns a stream of random int values. The number of values is unlimited.The ints(long streamSize) method returns a limited stream of random int values. The number of values is specified by the streamSize. For example, the following code prints 10 random integer numbers:The ints(long streamSize, int randomNumberOrigin, int randomNumberBound)method returns a limited stream of random int values between randomNumberOrigin (inclusive) and randomNumberBound (exclusive). For example, the code to print 10 random integer numbers between 1 and 10 can be written as compactly as:The Random class also provides similar methods for producing a stream of random long values.Now, you can see there are at least 3 different ways to generate random numbers between 1 and 100 in Java.Using Math.random() method:Using nextInt() method of Random class:And using ints() method of Random class:

Generate Unique Id Java

References:

Other Java Coding Tutorials:


About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook.

Suppose we wish to generate a sequence of 10000000 random 32-bit integers with no repeats. How can we do it?

I faced this problem recently, and considered several options before finally implementing a custom, non-repeating pseudo-random number generator which runs in O(1) time, requires just 8 bytes of storage, and has pretty good distribution. I thought I’d share the details here.

Approaches Considered

There are already several well-known pseudo-random number generators (PRNGs) such as the Mersenne Twister, an excellent PRNG which distributes integers uniformly across the entire 32-bit range. Unfortunately, calling this PRNG 10000000 times does not tend to generate a sequence of 10000000 unique values. According to Hash Collision Probabilities, the probability of all 10000000 random numbers being unique is just:

That’s astronomically unlikely. In fact, the expected number of unique values in such sequences is only about 9988367. You can try it for yourself using Python:

One obvious refinement is to reject random numbers which are already in the sequence, and continue iterating until we’ve reached 10000000 elements. To check whether a specific value is already in the sequence, we could search linearly, or we could keep a sorted copy of the sequence and use a binary search. We could even track the presence of each value explicitly, using a giant 512 MB bitfield or a sparse bitfield such as a Judy1 array.

Another refinement: Instead of generating an arbitrary 32-bit integer for each element and hoping it’s unique, we could generate a random index in the range [0, N) where N is the number of remaining unused values. The index would tell us which free slot to take next. We could probably locate each free slot in logarithmic time by implementing a trie suited for this purpose.

Brainstorming some more, an approach based on the Fisher-Yates Shuffle is also quite tempting. Using this approach, we could begin with an array containing all possible 32-bit integers, and shuffle the first 10000000 values out of the array to obtain our sequence. That would require 16 GB of memory. The footprint could be reduced by representing the array as a sparse associative map, such a JudyL array, storing only those x where A[x] ≠ x. Or, instead of starting with an array of all possible 32-bit integers, we could start with an initial sequence of any 10000000 sorted integers. In an attempt to span the available range of 32-bit values, we could even model the initial sequence as a Poisson process.

All of the above approaches either run in non-linear time, or require large amounts of storage. Several of them would be workable for a sequence of just 10000000 integers, but it got me thinking whether a more efficient approach, which scales up to any sequence length, is possible.

Generate Unique Random Key In Java Free

A Non-Repeating Pseudo-Random Number Generator

The ideal PRNG for this problem is one which would generate a unique, random integer the first 232 times we call it, then repeat the same sequence the next 232 times it is called, ad infinitum. In other words, a repeating cycle of 232 values. That way, we could begin the PRNG at any point in the cycle, always having the guarantee that the next 232 values are repeat-free.

Generate Unique Random Key In Java 10

One way to implement such a PRNG is to define a one-to-one function on the integers – a function which maps each 32-bit integer to another, uniquely. Let’s call such a function a permutation. If we come up with a good permutation, all we need is to call it with increasing inputs { 0, 1, 2, 3, … }. We could even begin the input sequence at any value.

For some reason, I remembered from first-year Finite Mathematics that when p is a prime number, (x^2,bmod,p ) has some interesting properties. Numbers produced this way are called quadratic residues, and we can compute them in C using the expression x * x % p. In particular, the quadratic residue of x is unique as long as (2x < p ). For example, when p = 11, the quadratic residues of 0, 1, 2, 3, 4, 5 are all unique:

Generate Unique Random Key In Java Download

As luck would have it, it also happens that for the remaining integers, the expression p - x * x % p fits perfectly into the remaining slots. This only works for primes p which satisfy (p equiv 3,bmod,4 ).

This gives us a one-to-one permutation on the integers less than p, where p can be any prime satisying (p equiv 3,bmod,4 ). Seems like a nice tool for building our custom PRNG.

In the case of our custom PRNG, we want a permutation which works on the entire range of 32-bit integers. However, 232 is not a prime number. /generate-a-public-key-mac.html. The closest prime number less than 232 is 4294967291, which happens to satisfy (p equiv 3,bmod,4 ). As a compromise, we can write a C++ function which permutes all integers below this prime, and simply maps the 5 remaining integers to themselves.

This function, on its own, is not the world’s best permutation – it tends to cluster output values for certain ranges of input – but it is one-to-one. As such, we can combine it with other one-to-one functions, such as addition and XOR, to achieve a much better permutation. I found the following expression works reasonably well. The intermediateOffset variable acts as a seed, putting a variety of different sequences at our disposal.

On GitHub, I’ve posted a C++ class which implements a pseudo-random number generator based on this expression.

I’ve also posted a working project to verify that this PRNG really does output a cycle of 232 unique integers.

So, how does the randomness of this generator stack up? I’m not a PRNG expert, so I put my trust in TestU01, a library for testing the quality of PRNGs, published by the University of Montreal. Here’s some test code to put our newly conceived PRNG through its paces. It passes all 15 tests in TestU01’s SmallCrush test suite, which I guess is pretty decent. It also passes 140/144 tests in the more stringent Crush suite.

Generate Unique Random Key In Java Download

Perhaps this approach for generating a sequence of unique random numbers is already known, or perhaps it shares attributes with existing PRNGs. If so, I’d be interested to find out. If you wanted, you could probably adapt it to work on ranges of integers other than 232 as well. Surfing around, I noticed that OpenBSD implements another non-repeating PRNG, though I’m not sure their implementation is cyclical or covers the entire number space.

Generate Random Key In Java

Incidentally, this PRNG is used in my next post, This Hash Table Is Faster Than a Judy Array.

Js Generate Unique Id

Do you know any other way to solve this problem? 256 bit wep key generator.