lundi 11 septembre 2017

Matching 2 strings chosen at random IF they don't exceed a limit of 12 characters?

I have a an array of Strings:

String[] possible_names = { "dog", "cat", "man", "woman", "boy", "girl", "table", "chair", "computer", "fat", "phone" };

I want to generate a character name by choosing 2 Strings from the array, and combining them, for example:

Random rn = new Random();
String first_name = possible_names[rn.nextInt(possible_names.length - 1)];
String last_name = possible_names[rn.nextInt(possible_names.length - 1)];
String full_name = first_name + last_name;

The problem is, I can't have it generate the full name if the full name exceeds 12 characters, or if first_name == last_name.

I know it would be easy to just check if the characters exceed 12 or first and last name are equal and return, but I want it to just.. try again I guess, if it fails.

I've figured out a way to do this, but I want it to be more efficient and not as memory consuming:

ArrayList<String> acceptable_last_names = new ArrayList<String>();
Random rn = new Random();
String first_name = possible_names[rn.nextInt(possible_names.length - 1)];
for (String s : possible_names) {
    if (s.length < (12 - first_name.length)) {
        if (!s.equalsIgnoreCase(first_name)) {
            acceptable_last_names.add(s);
        }
    }
}
last_name = acceptable_last_names.get(rn.nextInt(acceptable_last_names.size());

I don't know if that code EXACTLY would work because I typed it here but I know I could do it similarly to that. My question is, is there a more efficient way to achieve this?




Aucun commentaire:

Enregistrer un commentaire