vendredi 17 mars 2017

Generate all possible strings optimization

I have to generate a list of every string possible (given a specific string to pick characters from), the first method I came up with is this one:

public String getRandomLetters(Integer size, String range){
    String word = "";
    Random r = new Random();

    for (int i = 0; i < size; i++) {
        word += range.charAt(r.nextInt(range.length()));
    } 

    return word;
}

Using like this: getRandomLetters(2, "abc");

This will return a string of 2 letters.

Now, with this given range I have to generate a list of random strings. This list of words must not have repeatable words, must start by 1 character and when out of possibilities just add another.

Im trying this:

public List<String> getListOfRandomWords(Integer listLenght){
    String range = "abc"; //abcdefghijklmnopqrstuvwxyz
    Integer rangeLenght = range.length();

    List<String> words = new ArrayList();
    int counter = 1;

    int possibilities = (int) Math.pow(Double.valueOf(rangeLenght), Double.valueOf(counter));

    String word = "";

    for (int i = 0; i < listLenght; i++) {
        word = getRandomLetters(counter, range);

        while (words.contains(word)) {
            if(words.size() == possibilities){
                counter++;
                possibilities += (int) Math.pow(Double.valueOf(rangeLenght), Double.valueOf(counter));
            }
            word = getRandomLetters(counter, range);
        }

        words.add(word);
    }

    return words;
}

To run this:

        List<String> testList = getListOfRandomWords(20);

        for (String block : testList) {
            System.out.println(block);
        }

Output:

c
b
a
cc
ca
aa
bb
ba
ac
bc
ab
cb
bcc
cca
bac
aab
bab
cbb
baa
bcb

The output is ok and method works properly, my only concern is while(randomLetters.contains(randomLetter)), is this the most optimal way to check for duplicate values?

PD: I can't use a sum to make this easier and generate the strings in order, they must come in random order.




Aucun commentaire:

Enregistrer un commentaire