• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 964
  • Last Modified:

how to generate a unique number ?

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
cofactor
Asked:
cofactor
  • 4
  • 4
  • 2
  • +2
2 Solutions
 
Amitkumar PSr. ConsultantCommented:
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
 
CEHJCommented:
0
 
krakatoaCommented:
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
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
cofactorAuthor Commented:
@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
 
CEHJCommented:
What do you mean by 'special characters'?
0
 
cofactorAuthor Commented:
>>What do you mean by 'special characters'?

its keyboard special characters.
0
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
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
 
CEHJCommented:
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
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
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
 
CEHJCommented:
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
 
cofactorAuthor Commented:
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
 
cofactorAuthor Commented:
excellent
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

  • 4
  • 4
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now