Here's the modified solution that dynamically calculates all parameters based on the alphabet:
import java.util.concurrent.ThreadLocalRandom;
public class RandomStringGenerator {
private static final char[] ALPHANUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_".toCharArray();
// Calculate parameters based on alphabet size
private static final int ALPHABET_SIZE = ALPHANUM.length;
private static final int BITS_PER_CHAR = Integer.SIZE - Integer.numberOfLeadingZeros(ALPHABET_SIZE - 1);
private static final int MASK = (1 << BITS_PER_CHAR) - 1;
private static final double ENTROPY_PER_CHAR = Math.log(ALPHABET_SIZE) / Math.log(2);
private static final int LENGTH = (int) Math.ceil(122.0 / ENTROPY_PER_CHAR);
public static String randomAlphanumeric() {
final char[] buf = new char[LENGTH];
int idx = 0;
final ThreadLocalRandom rnd = ThreadLocalRandom.current();
while (idx < LENGTH) {
long r = rnd.nextLong();
// Extract as many characters as possible from this long
for (int i = 0; i < 64 / BITS_PER_CHAR && idx < LENGTH; i++) {
int charIdx = (int) (r & MASK);
// Use rejection sampling to avoid bias
if (charIdx < ALPHABET_SIZE) {
buf[idx++] = ALPHANUM[charIdx];
}
r >>>= BITS_PER_CHAR;
}
}
return new String(buf);
}
// Optional: method to show calculated parameters
public static void showParameters() {
System.out.printf("Alphabet size: %d%n", ALPHABET_SIZE);
System.out.printf("Bits per extraction: %d%n", BITS_PER_CHAR);
System.out.printf("Entropy per char: %.2f bits%n", ENTROPY_PER_CHAR);
System.out.printf("String length: %d chars%n", LENGTH);
System.out.printf("Total entropy: %.2f bits%n", LENGTH * ENTROPY_PER_CHAR);
}
}
How it works:
- ALPHABET_SIZE: Simply the length of your character array
- BITS_PER_CHAR: Calculated as
ceil(log2(ALPHABET_SIZE)) using bit manipulation
- MASK: Creates a bitmask with the right number of bits
- ENTROPY_PER_CHAR: Actual entropy per character =
log2(ALPHABET_SIZE)
- LENGTH: Calculated to achieve ~122 bits of entropy
Examples with different alphabets:
// Original (62 chars): "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
// → 6 bits per extraction, 5.95 entropy per char, 21 char length
// With underscore (63 chars): "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_"
// → 6 bits per extraction, 5.98 entropy per char, 21 char length
// With symbols (66 chars): "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-."
// → 7 bits per extraction, 6.04 entropy per char, 21 char length
Now you can modify the ALPHANUM array (add _, -, ., etc.) and the method automatically adjusts all parameters while maintaining the same entropy level and efficiency!