Skip to content

Instantly share code, notes, and snippets.

@ok3141
Created September 29, 2020 17:36
Show Gist options
  • Save ok3141/3d23e9464965de3e4b1711034109e6ef to your computer and use it in GitHub Desktop.
Save ok3141/3d23e9464965de3e4b1711034109e6ef to your computer and use it in GitHub Desktop.
public static String generatePin(int n, int k, Random random) {
StringBuilder sb = new StringBuilder();
while (k-- > 0) {
sb.append("0123456789");
}
char[] result = new char[n];
for (int i = 0; i < n; ++i) {
int index = random.nextInt(sb.length());
result[i] = sb.charAt(index);
sb.deleteCharAt(index);
}
return new String(result);
}
// usage
String pin = generatePin(6, 3, new SecureRandom());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment