Strict Constrained Random String Generation Algorithm - Java

I am trying to create a program to create an arbitrary account name for a user. The user clicks the button and he copies the account name to the clipboard. The GUI component works, but I just can't come up with a better way to handle random string generation.

Allowed characters in the username: AZ az _

There are no numbers, other characters and two identical characters in a string.

Must be six in length.

My idea:

create an array of characters: [ _, a, b, c, d ... etc ] Generate a random integer between 0 and array.length - 1 and pick the letter in that slot. Check the last character to be added into the output String, and if it the same as the one we just picked, pick again. Otherwise, add it to the end of our String. Stop if the String length is of length six. 

Is there a better way? Perhaps with regex? I have a feeling that I think doing it here is very bad.

+5
source share
1 answer

I do not see anything wrong with your proposed algorithm (except that you need to process the first character you add without checking if you have already added it). You can also extract it into the static method and use Random like,

 static Random rand = new Random(); static String getPassword(String alphabet, int len) { StringBuilder sb = new StringBuilder(len); while (sb.length() < len) { char ch = alphabet.charAt(rand.nextInt(alphabet.length())); if (sb.length() > 0) { if (sb.charAt(sb.length() - 1) != ch) { sb.append(ch); } } else { sb.append(ch); } } return sb.toString(); } 

Then you could call it something like

 public static void main(String[] args) { StringBuilder alphabet = new StringBuilder(); for (char ch = 'a'; ch <= 'z'; ch++) { alphabet.append(ch); } alphabet.append(alphabet.toString().toUpperCase()).append('_'); String pass = getPassword(alphabet.toString(), 6); System.out.println(pass); } 
+3
source

Source: https://habr.com/ru/post/1239673/


All Articles