Reputation: 357
I did the stuff like this but not working. the base48Encode method parameter I have passed the current system time in milli secs
private static final String CHARACTER_SET = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";
public static String base48Encode(double d) {
Double num = Double.valueOf(d);
Integer length = CHARACTER_SET.length();
String encodeString = new String();
while (num > length) {
encodeString = CHARACTER_SET.charAt(num.intValue() % length) + encodeString;
num = Math.ceil(new Double(num / length) - 1);
}
encodeString = CHARACTER_SET.charAt(num.intValue()) + encodeString;
return encodeString;
}
Upvotes: 2
Views: 2370
Reputation: 7391
I won't get duplicate values in any scenario.
It's not possible to 100% guarantee a unique value (especially given a string of 7 characters) due to the Birthday Paradox. Given a character set containing 48 characters, selecting 7 at random, you'd have a 1% chance of collision after only 110,000 random values.
You can help mitigate this by doing two things.
Using a character set of 64 characters and selecting 10 at random would greatly decrease your chance of a collision, down to a 1% after 160,000,000 random values.
Rather than using currentTimeMillis
to generate a value, which would cause a collision if you generated two values within the same millisecond, I'd suggest just using the Random
class (which is seeded from the current time down to the nanosecond).
private static final String CHARACTER_SET = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";
private static Random rnd = new Random();
public static String randomString(int length){
StringBuilder builder = new StringBuilder();
for(int i = 0; i < length; i++){
builder.append(CHARACTER_SET.charAt(rnd.nextInt(CHARACTER_SET.length())));
}
return builder.toString();
}
Upvotes: 5