Skip to content

Instantly share code, notes, and snippets.

@bbjubjub2494
Created June 2, 2020 18:11
Show Gist options
  • Save bbjubjub2494/df89a9eb8c001f5a15a498392a4a4120 to your computer and use it in GitHub Desktop.
Save bbjubjub2494/df89a9eb8c001f5a15a498392a4a4120 to your computer and use it in GitHub Desktop.
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class poc {
private static final String ALPHA_UPPER_CASE = "abcdefghijklmnopqrstuvwxyz".toUpperCase();
private static final String NUMERIC= "0123456789";
private static final Integer CODE_SIZE = 6;
private static final SecureRandom sRandom = new SecureRandom();
public static void main(String[] args) {
System.out.println(generateCode());
}
private static final List<Character> ALPHA_NUMERIC_CHAR_ARRAY = String
.format(
"%s%s",
ALPHA_UPPER_CASE,
NUMERIC)
.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.toList());
public static String generateCode() {
System.out.println("Generating random 6-alphanum code");
final List<Character> characters = getShuffledAlphaNumList();
for (int i = 0; i < characters.size(); i++) {
System.out.println(Integer.toString(i) + ": " + characters.get(i));
}
System.out.println("characters size = " + characters.size());
System.out.println("ALPHA_NUMERIC_CHAR_ARRAY size - 1 = " + Integer.toString((ALPHA_NUMERIC_CHAR_ARRAY.size()-1)));
System.out.println(characters.get((ALPHA_NUMERIC_CHAR_ARRAY.size() - 1)) + " is unreachable");
String alphaNum = "";
for (int i = 0; i < CODE_SIZE; i++) {
alphaNum += characters.get(sRandom.nextInt(ALPHA_NUMERIC_CHAR_ARRAY.size()-1)).toString();
}
return alphaNum;
}
/**
* @return return a shuffled copy of ALPHA_NUMERIC_CHAR_ARRAY
*/
protected static List<Character> getShuffledAlphaNumList() {
final ArrayList<Character> tempAlphaNumList = new ArrayList<>(ALPHA_NUMERIC_CHAR_ARRAY);
Collections.shuffle(ALPHA_NUMERIC_CHAR_ARRAY,sRandom);
return tempAlphaNumList;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment