Search code examples
javaarraysstringduplicatesunique

Create unique name from Array without duplicates


I want to to try to create unique names from an array.

public String[] firstname = {"Ben", "Pe", "To", "Jau",...};

And here I create a String (Helper.random is just a method to pick a random element). I want to avoid a name like "Benben" or "Pepe"...

String name1 = firstname[Helper.random(0, firstname.length)];
String name2 = firstname[Helper.random(0, firstname.length)];

if(name1.equals(name2)) {
    name1 = firstname[Helper.random(0, firstname.length)];
}

Now I am stuck. I create some names but then i get duplicates like "Benpe" here and "Benpe" there.

How can i create unique names, like:

CREATE A STRING name FROM THIS ARRAY IN ALL COMBINATION ("Bento", Benpe", "Bento".....)
IF YOU GET A DUPLICATE ("Bento", Bento") ADD ANOTHER ELEMENT TO name ("Bentope")


Solution

  • One quick solution is to change the if into a loop. You need to keep trying in case you get the same name several times in a row.

    while (name1.equals(name2)) {
        name1 = firstname[Helper.random(0, firstname.length)];
    }
    

    Note that neither the if nor the while ideas match the spec. You're supposed to add a third item to the name, not replace name1.