Link to home
Start Free TrialLog in
Avatar of cofactor
cofactor

asked on

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)
Avatar of Am P
Am P
Flag of India image

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

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.
Avatar of cofactor
cofactor

ASKER

@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.
What do you mean by 'special characters'?
>>What do you mean by 'special characters'?

its keyboard special characters.
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?
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' ...
ASKER CERTIFIED SOLUTION
Avatar of mccarl
mccarl
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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 ?
excellent