Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created January 7, 2020 04:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/e5c74f9811e2a09369acba11950f2876 to your computer and use it in GitHub Desktop.
Save parzibyte/e5c74f9811e2a09369acba11950f2876 to your computer and use it in GitHub Desktop.
private static String obtenerPasswordAleatoria(boolean conRepetidos, int longitud) {
String muestra = "0123456789";
Random random = new Random(System.currentTimeMillis());
String pass = "";
for (int x = 0; x < longitud; x++) {
// Tomamos un dígito aleatorio
int indiceAleatorio = random.nextInt(muestra.length());
char digitoAleatorio = muestra.charAt(indiceAleatorio);
// Si no quieren repetidos...
if (!conRepetidos) {
// Mientras que en la cadena ya exista el carácter que acabamos de generar
while (pass.indexOf(digitoAleatorio) != -1) {
// Generamos otro
indiceAleatorio = random.nextInt(muestra.length());
digitoAleatorio = muestra.charAt(indiceAleatorio);
}
}
// De cualquier forma, agregamos el dígito a la cadena
pass += digitoAleatorio;
}
return pass;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment