Solved

how to generate a unique  number ?

Posted on 2013-12-06
12
650 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 20

Expert Comment

by:Amitkumar Panchal
Comment Utility
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
Comment Utility
0
 
LVL 16

Expert Comment

by:krakatoa
Comment Utility
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
Comment Utility
@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
Comment Utility
What do you mean by 'special characters'?
0
 

Author Comment

by:cofactor
Comment Utility
>>What do you mean by 'special characters'?

its keyboard special characters.
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 35

Expert Comment

by:mccarl
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
excellent
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
The viewer will learn how to implement Singleton Design Pattern in Java.

763 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

13 Experts available now in Live!

Get 1:1 Help Now