4

What java library are there provides the the facility to generate unique random string combination from a given set of characters?

Say I have these set of characters: [a-zA-Z0-9]

And I need to generate 4-character string from this set that is less likely to collide.

c00kiemon5ter
  • 16,994
  • 7
  • 46
  • 48
quarks
  • 33,478
  • 73
  • 290
  • 513
  • You may want to take a look at [this question/answer](http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string-in-java) too – c00kiemon5ter Nov 16 '11 at 12:09
  • @xybrek: 62**4 ain't that much. Collisions are going to be likely. – TacticalCoder Nov 16 '11 at 12:10
  • java.math.BigInteger, java.security.SecureRandom can solve your query. See an example at `http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string-in-java/41156#41156` – Ravinder Reddy Nov 16 '11 at 12:15

3 Answers3

8

Apache Commons Lang has a RandomStringUtils class with a method that takes a sequence of characters and a count, and does what you ask. It makes no guarantee of collision avoidance, though, and with only 4 characters, you're going to struggle to achieve that.

skaffman
  • 398,947
  • 96
  • 818
  • 769
3

And I need to generate 4-character string from this set that is less likely to collide.

Less likely than what? There are 62^4 = 14.8 million such strings. Due to the birthday paradox, you get about a 50% chance of a collision if you randomly generate 3800 of them. If that's not acceptable, no library will help you, you need to use a longer string or establish uniqueness explicitly (e.g. via incrementing an integer and formatting it in base 62).

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
  • Actually [a-zA-Z0-9] are 62 characters, so it's 62^4 ore 14.8 millions. Which may or may not be plenty. If you know you're not going to generate more than 62 on any one day, you can use the first three characters to count the days and the last as a counter in the day, and you're good for the next 652 years. – PapaFreud Nov 16 '11 at 12:16
1

if you'd be ok with a longer hash, you'd certainly be able to find some md5 libraries. It's most common for this kind of task. A lot of web sites use it to generate password hashes.

user980058
  • 511
  • 7
  • 18