vendredi 14 juillet 2017

Generate unique string within specific length range

I faced some difficulties to figure out how to generate unique string within range [1;200) length. What i've done so far doesn't works exactly how i expected.

Source code:

public static String generateRandString() {

    String STRING_TOKENS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
    StringBuilder stringBuilder = new StringBuilder();
    Random random = new Random();
    while(stringBuilder.length() <= 200) {
        int index = (int) random.nextFloat() * STRING_TOKENS.length();
        stringBuilder.append(STRING_TOKENS.charAt(index));
    }

    return stringBuilder.toString();
}

Requesting 20 generated strings returns every time "AAAAAAAA" string probably of 200 symbols length

Expected output:

A7898as7sd6as5da
as87asd67
768asjhg435GhA900324
2g2j3h4gjhgAKL*78a9dd879234
3B234
1

Some restrictions:

  1. No additional libraries usage
  2. Should be written using Java 1.6

Assist required.




Aucun commentaire:

Enregistrer un commentaire