Strategy for generating a random char [A-Z]
used in all these solutions:
private static char rnd() {
return (char) ('A' + ThreadLocalRandom.current().nextInt('Z'-'A' + 1));
}
Anyway, if it's always going to have a length of nine, then I wouldn't overthink it:
public static String gen() {
return String.format("%s-%s-%s", triplet(), triplet(), triplet());
}
private static String triplet() {
return String.format("%c%c%c", rnd(), rnd(), rnd());
}
If it needs to scale depending on input, here's one of the many possible dynamic solutions:
public static String gen(int len) {
if(len < 1)
return "";
final char[] out = new char[len + ((len-1)/3)];
fill(out, 0);
return new String(out);
}
private static void fill(char[] chars, int idx) {
if(idx > (chars.length - 1))
return;
chars[idx] = ((idx+1)%4==0) ? '-' : rnd();
fill(chars, idx+1);
}
There's also this variant which is a bit less efficient because it creates a new String
each time, but I like it because it's immutable:
public static String gen(final int len) {
if(len < 1)
return "";
return gen("", 0, (len + ((len-1)/3)));
}
private static String gen(final String out, final int idx, final int max) {
if(idx >= max)
return out;
return gen(out + (((idx+1)%4==0) ? '-' : rnd()), idx+1, max);
}