You can use a Java transformation to generate unique and random numeric keys within a specific range. You can use the numeric keys for the primary key field of a target table. For example, you have order records in a flat file. You need to assign unique, random primary keys. In this tutorial, we're going to show how to generate a random string in Java – first using the standard Java libraries, then using a Java 8 variant, and finally using the Apache Commons Lang library.

  1. Generate Unique Random Key In Java Pdf
  2. Java Random Number 1 100
  3. Js Generate Unique Id
  4. Generate Random Key In Javascript

Generate Unique Random Key In Java Pdf

Greenhorn
posted 8 years ago
Hello,
I need to generate a number, based on the primary key of an table, which will be used as an external reference (e.g. to label a product, or generate a barcode).
The number will be stored on database and later used to retrieve the actual record it was derived from.
The number has to be of a fixed length, say max 8 characters to minimize the length of the barcode.
Are there any APIs I can use to generate this number?
The solution need not imperatively derive the number form the primary key; I only need to ensure it will be unique across all records.
Thanks,
Shehzaad
Marshal
posted 8 years ago
How can you be sure the numbers will be unique? You must ensure the number of entries is fewer than the range of the numerical type.
Why don’t you simply use the key from the table? DBMSs are designed to work out that sort of thing quickly.
Marshal
posted 8 years ago
Bartender
posted 8 years ago

Campbell Ritchie wrote:How can you be sure the numbers will be unique?


Well, if it's a primary key, the chances are that it has to be (although some databases do allow tables with no key).
@shehzaad: First off, do you actually need a number? Or will a code do?
Second: is the barcode itself a numeric code? 8 digits seems awfully short for any sort of standard barcode (eg, a UPC or SKU). If so, I'd just use it and not worry about the length (a Javalong can hold numbers up to 18 digits).
Winston

'Leadership is nature's way of removing morons from the productive flow' - Dogbert
Articles by Winston can be found here

Greenhorn
posted 8 years ago
Thanks! its actually my first ever go at forums!
some precisions:
1) I need to keep the length of the reference to a minimum, so that the 'barcode lines' generated are also a minimum. (I am using code-39)
I tried using a hash (md5, sha-1) of the primary key, but this generates 32-character long hex strings.
2) Any of the characters allowed by code-39 will do; I do not have to stick to purely numbers.
3) I have to stick to a java solution, not to a db-tied one.
Java Cowboy
posted 8 years ago

shehzaad goonoo wrote:The number will be stored on database and later used to retrieve the actual record it was derived from.


shehzaad goonoo wrote:I tried using a hash (md5, sha-1) of the primary key, but this generates 32-character long hex strings.


If this is one of your requirements, then using a hash code is not going to work.
Hashing algorithms such as MD5 and SHA-1 are one way. You can calculate the hash over some data, but it is impossible to get back the original data if you have only the hash. So if you need to be able to find the record back later, then that's not possible when you use a hash. You'll need some algorithm that is reversible.
Bartender
posted 8 years ago

shehzaad goonoo wrote:1) I need to keep the length of the reference to a minimum, so that the 'barcode lines' generated are also a minimum. (I am using code-39)
I tried using a hash (md5, sha-1) of the primary key, but this generates 32-character long hex strings.


So, wait a minute..
Are you trying to find a way of generating a code-39 barcode that will cover your entire stock (or whatever) in 8 characters? because that's a completely different question. And the answer to that is almost certainly 'yes'.
Or are you trying to find a way of condensing a code-39 barcode to a unique 8-digit number? The answer to that is most assuredly 'NO'.
Or are you looking for something in between (like a hashcode) - an 8-digit number that is probably unique. The answer to thatGenerate unique random key in java free is, absolutely, 'YES'.
I think you need to tell us exactly what it is you want, and then move on from there.
It should probably also be pointed that 'keep the length of the reference to a minimum, so that the 'barcode lines' generated are also a minimum' is a very artificial (and arbitrary) restriction that has no basis in normal stock-keeping, so you might want to revise it.
Winston

'Leadership is nature's way of removing morons from the productive flow' - Dogbert
Articles by Winston can be found here

Greenhorn
posted 8 years ago
  • 1
Think it will be better if I focus on a single requirement. Lets forget about the barcode stuff.
To put it simply:
1. as input, I have a table's primary key
2. as output, I want another unique number (It is not a requirement for it to be based on the primary key or not, as long as it stays unique across the rows of the table) of a reasonable length, say 16 digits max.
3. It has to be a Java solution
Thanks
Bartender
posted 8 years ago

shehzaad goonoo wrote:1. as input, I have a table's primary key
2. as output, I want another unique number (It is not a requirement for it to be based on the primary key or not, as long as it stays unique across the rows of the table) of a reasonable length, say 16 digits max.
3. It has to be a Java solution.


OK, now you're getting the idea. Some questions back to you (based on your numbering):
1:
(a) How long is the primary key?
(b) Is it numeric or alphanumeric?
(c) Does it contain any redundancy (for example, a prefix which is the same for all items)?
2:
(a) Does it have to be a number? Or can it be a code?
The simplest form of unique identifier is a sequence number and, unless you have a computer bigger than my apartment block, that will almost certainly fit into 16 digits. You may however, need a way to persist the 'last number used' value.
Java also provides a UUID class, which is designed specifically for creating unique IDs. In fact, it is not guaranteed to produce a unique ID, but the chances of it doing so are so small as to be basically nil. Also, the only automated form is a time-based UUID. Unfortunately, a UUID consists of two longs (ie, 32 hexadecimal digits or 36 decimals) so it's probably too long for your purposes.
Finally, you could generate one yourself. One possible suggestion:
42 bits contains enough space to store approximately 135 years worth of milliseconds.
10 bits contains enough space to store the fraction of a millisecond that makes a microsecond.
which leaves 11 bits left over to store a random number between 0 and 2047.

Java Random Number 1 100

Highly likely to be unique (NOT guaranteed though), fits in a long (18 digits), and could be generated easily and quickly from System.currentTimeMillis(), System.nanotime() and Random.nextInt(2048) (or indeed, simply cycling a sequence). Furthermore, if you put it together properly, it will sort in the order that IDs were created (or very close).
Personally, I'd look at a sequence number first though.
Winston

'Leadership is nature's way of removing morons from the productive flow' - Dogbert
Articles by Winston can be found here

Greenhorn
posted 7 years ago
Sorry for the delay in following up with this topic. Actually, due to tight deadlines, back in March, I came up with a 'temporary solution' and delivered that module, intending to look into that at a later stage.
But like every other 'temporary solution', it is in production since 3 weeks now! I am therefore sharing the 'solution' which went into prod; it would be great to have your views on it, as well as a heads-up on any imminent crash!
Basically, a 9-digit 'code' is now being generated using Java's Random class, passing as the seed, the primary-key of a freshly created barcode row:
Sheriff
posted 7 years ago
Why can't you use the primary key 'as is'? It would be the simplest solution. Do you want to prevent obtaining the primary key from the code?
(Your current code doesn't guarantee uniqueness, but you're very probably aware of that.)

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.

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.

Js Generate Unique Id

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:

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. 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.

The latest version Windows 7 Professional Product Key will boost up all over the performance of your system for the lifetime. Microsoft has launched other operating system like Windows 8, Windows 8.1 and Windows 10 as well. Now Windows 7 Professional Product Key 32 and 64 Bit. Mar 09, 2020  The process of activating free Windows 7 product key is an easy task. The primary task that must be on the ground is for you to have downloaded a key generator. Let us take a look at the process together: Open your system and allow it to boot up. Generating product key for windows 7 pro 64 bit upgrade free

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.

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.

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

Generate Random Key In Javascript

Do you know any other way to solve this problem?