Every combination of characters from dynamic list

Viewed 145

I am stuck with a logic. I have a free text dropdown where users are free to enter up to 5 characters. Now every character has unicode accent characters associated to it. I generate unicode characters for the list associated for the characters. Now I want to generate all possible combinations with the characters from the list. I am a bit stuck since the list is generated dynamically. How do I possibly get to know which list should be iterated first? Below is my code.

//example String key="za";
if (key!=null) {
    List<Character> characList = key.chars()
                                    .mapToObj(c -> (char) c)
                                    .collect(Collectors.toList());//[z, a]
    List<List<String>> mainList = new ArrayList<List<String>>();
    for (Character characterObj:characList) {
        List<String> subList = new ArrayList<String>();
        Collection<String> charColl = unicodeMap.getCollection(characterObj.toString());
        subList = new ArrayList(charColl);//first iteration we get [ż, ź, ž] second iteration we get [à, á, â, ã, ä, å, ą, ă, ā]
        mainList.add(subList);//[[ż, ź, ž], [à, á, â, ã, ä, å, ą, ă, ā]]
    }
}

Now i want to generate combination of String from [[ż, ź, ž], [à, á, â, ã, ä, å, ą, ă, ā]]. The String could have been azstu,etc. How do i iterate so that it will take care of all combinations from the associations of entered String. Please advise.

Desired output from the example String:-

żà
żá
żâ
żã
żä
żå
żą
żă
żā
.
.
.
1 Answers

A way can be recursively generate the string. Traverse the character's collection list by index and looping for every sublist.

List<String> genr(List<List<String>> list, int index, String now) {
    if (index >= list.size()) {
      return Arrays.asList(now);
    }
    List<String> subList = list.get(index);
    List<String> res = new ArrayList<>();
    for (String value : subList) {
      res.addAll(genr(list, index + 1, now + value));
    }
    return res;
  }

And call like

List<List<String>> mainList = new ArrayList<List<String>>();
mainList.add(Arrays.asList("ż", "ź", "ž"));
mainList.add(Arrays.asList("à", "á", "â", "ã", "ä", "å", "ą", "ă", "ā"));
List<String> data = genr(mainList, 0, "");

Output: [żà, żá, żâ, żã, żä, żå, żą, żă, żā, źà, źá, źâ, źã, źä, źå, źą, źă, źā, žà, žá, žâ, žã, žä, žå, žą, žă, žā]

Demo here

Related