lundi 4 mai 2020

Efficiently generating random numbers

I'm trying to generate 7 random numbers between 0-9 in java. I found 3 solution:

the first solution using RandomStringUtils:

RandomStringUtils.randomNumeric(7);

the second solution:

public static String createRandomCode(int codeLength, String id) {
    return new SecureRandom().ints(codeLength, 0, id.length()).mapToObj(id::charAt).map(Object::toString)
                .collect(Collectors.joining());
}
createRandomCode(7, "0123456789");

the third solution:

private static char[] HEX_VALUES = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
public static char[] createRandomHexValues(int nValues) {
    char[] ret = new char[nValues];
    for (int i = 0; i < nValues; i++) {
        SecureRandom randomGenerator = new SecureRandom();
        ret[i] = HEX_VALUES[randomGenerator.nextInt(HEX_VALUES.length)];
    }
    return ret;
}
createRandomHexValues(7);

this 3 solutions work fine, but the question is which one of them is the most efficient and fast.




Aucun commentaire:

Enregistrer un commentaire