Solved

how to generate a unique  number ?

Posted on 2013-12-06
12
665 Views
Last Modified: 2013-12-14
I want to generate a unique number.

(a) maximum 20 characters.

(b) alphanumeric as well as special  characters only.


I am thinking a code like this ...

UUID uid = UUID.randomUUID();
String id = uid.toString();

Can you please suggest how I may  get a unique id  following (a) and (b)
0
Comment
Question by:cofactor
  • 4
  • 4
  • 2
  • +2
12 Comments
 
LVL 21

Expert Comment

by:Amitkumar Panchal
ID: 39700837
you can try below code:

private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

public static String generateRandomID(int counter) {
	StringBuilder builder = new StringBuilder();
	while (counter-- != 0) {
		int index = (int)(ALPHA_NUMERIC_STRING.length() * Math.random());
		builder.append(ALPHA_NUMERIC_STRING.charAt(index));
	}
	return builder.toString();
}

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 39701491
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 39702453
Course, the only really unique numbers are in the range of -infinity to +infinity.

And once you introduce any non-numeric character, you kill any chance of true randomness stone dead.
0
 

Author Comment

by:cofactor
ID: 39702599
@CHEJ,

I am using that UUID already .  I want to put  two constraints there.  Please see the query again.


for your information , you know I  want to generate a unique number  to set a transaction id  for a payment gateway.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 39702817
What do you mean by 'special characters'?
0
 

Author Comment

by:cofactor
ID: 39702947
>>What do you mean by 'special characters'?

its keyboard special characters.
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 35

Expert Comment

by:mccarl
ID: 39705001
What about just doing this...
String id = UUID.randomUUID().toString().subString(0, 20);

Open in new window

Or are you saying that you specifically WANT to use the full aphabet and special characters?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 39705062
I am using that UUID already .  I want to put  two constraints there.  Please see the query again.

The first constraint is met. As far as the other one is concerned, i find it slightly odd that you're happy to ahve characters like '&'. '%' in a 'unique number' ...
0
 
LVL 35

Accepted Solution

by:
mccarl earned 200 total points
ID: 39705076
I've only just read your subsequent comment on the intended use for this value. So I am guessing that in addition to the 2 constraints that you initially stated, a 3rd constraint is that it should minimise (to the extent possible) the possibilty of any collisions, ie. the possibility of the same value being generated by as low as possible.

The only way that you could guarantee uniqueness (in a certain range of values) is if you have one source of truth and that source is the only one that allocates id values. Often this is not possible, as I am assuming in your case, and so some scheme like this is required. Note though that in this case you can't "guarantee" uniqueness. The only thing you can do is take measures to reduce to likelyhood of the same value being generated.

If the above is the case, that you require as low a possibly of uniqueness that you can, then disregard my previous comment. It discards information and this in combination with the fact that it doesn't use the full range of possible characters that you allow, means that there are other ways to reduce the risk of getting the same value.


First question, is uniqueness dependant on the upper/lower case of the alpha characters, ie. are the two values "ABc123" and "abc123" considered unique or the same?

Amit answer is pretty good however I would make a few changes...
private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&*()-=_+[]{}\|:\";'<>?,./`";   // Include here any other special characters (or omit any of these characters) so that this is the FULL set of possible output characters
private SecureRandom random = new SecureRandom();

public static String generateRandomID() {
	StringBuilder builder = new StringBuilder();
	for (int i = 0; i < 20; i++) {
		int index = random.nextInt(ALPHA_NUMERIC_STRING.length());
		builder.append(ALPHA_NUMERIC_STRING.charAt(index));
	}
	return builder.toString();
}

Open in new window

Notes about the above...

On the first line, include as many characters that you allow in the output id value. The more characters that are used here, reduces the possibility of getting the same number out of the generator.

On line 2 of the above, we create a SecureRandom object, which may be able to provide a more appropriate random number generator to what Math.random() uses. SecureRandom is what is used in UUID.randomUUID() so the above code should give at least the same guarantees about uniqueness as UUID does.

On line 7, .nextInt() may provide a more uniform distribution of index values than getting a random double value and multiplying it by the length of the characters string. The also reduces the possibility of output collisions.
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 200 total points
ID: 39706515
For the sake of readability, you might like to omit special characters. With digits and upper/lower case, you should get enough of the right amount of collision probability. If you generate a 20-char string, the probability (assuming proper randomness) of the next one colliding is 1 in 704423425546998022968330264616370176^2, or to put it another way - unlikely
0
 

Author Comment

by:cofactor
ID: 39718670
I have not used these solutions  ...because the payment gateway now  sending a unique transaction id   which I can re-use in my system.

anyway,  I liked the solutions ....hence accepting both.


by the way ..

@CHEJ ,  could you please tell  

..........If you generate a 20-char string.............

how ?  with UUID or without UUID ?  if with UUID , then how  you can specify that limit ?
0
 

Author Closing Comment

by:cofactor
ID: 39718671
excellent
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This video teaches viewers about errors in exception handling.

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now