How to generate all permutations of a List<List<String>>? [duplicate]

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-08 11:12:37

问题


I am trying to generate all permutations of a List<List<String>> but I am not getting unique permutations.

My List<List<String>> looks something like

[
 [Test, Test 1, Test 2],
 [Apple, Sandwich, Banana],
 [Cake, Ice Cream, Fruit]
] 

I am trying to get every combination possible for each List<String within the parent List<String>. So, for example, the first instance should have:

[Test, Test 1, Test 2]
[Test, Test 2, Test 1]
[Test 2, Test, Test 1]
[Test 2, Test 1, Test]
[Test 1, Test, Test 2]
[Test 1, Test 2, Test]

Right now, my attempt will just iterate and repeat the elements without changing the order so [Test, Test 1, Test 2] will just be repeated for the size of the parent List<String>. This is my approach. Any help is appreciated:

List<List<String>> allPerms = parentList.stream().map(line -> parentList.stream()).flatMap(l -> l.filter(j -> !j.equals(l))).collect(Collectors.toList());

回答1:


Use CollectionUtils.permutations

public static void showAllPermuteByCommons(List<String> list) {
    CollectionUtils.permutations(list) //
            .stream() //
            .forEach(System.out::println);
}

Or backtrack

public static void permute(List<String> list, int left, int right) {
    if (left == right) {
        System.out.println(Arrays.toString(list.toArray()));
        return;
    }
    for (int j = left; j <= right; j++) {
        Collections.swap(list, left, j);
        permute(list, left + 1, right);
        Collections.swap(list, left, j);
    }
}

public static void showAllPermute(List<String> list) {
    int size = list.size();
    permute(list, 0, size - 1);
}

Test

List<List<String>> list = new ArrayList<>();
list.add(Arrays.asList("Test", "Test 1", "Test 2"));
list.add(Arrays.asList("Apple", "Sandwich", "Banana"));
list.add(Arrays.asList("Cake", "Ice Cream", "Fruit"));

// list.forEach(t -> showAllPermuteByCommons(t));
list.forEach(t -> showAllPermute(t));

Ouput

[Test, Test 1, Test 2]
[Test, Test 2, Test 1]
[Test 2, Test, Test 1]
[Test 2, Test 1, Test]
[Test 1, Test 2, Test]
[Test 1, Test, Test 2]
[Apple, Sandwich, Banana]
[Apple, Banana, Sandwich]
[Banana, Apple, Sandwich]
[Banana, Sandwich, Apple]
[Sandwich, Banana, Apple]
[Sandwich, Apple, Banana]
[Cake, Ice Cream, Fruit]
[Cake, Fruit, Ice Cream]
[Fruit, Cake, Ice Cream]
[Fruit, Ice Cream, Cake]
[Ice Cream, Fruit, Cake]
[Ice Cream, Cake, Fruit]


来源:https://stackoverflow.com/questions/58314196/how-to-generate-all-permutations-of-a-listliststring

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!