简体   繁体   English

在 java 中查找给定集合的所有子集,并按此顺序

[英]finding all subsets of a given set in java and in this order

actually I want to write all subsets of a given set in this way:实际上我想以这种方式编写给定集合的所有子集:

for example if my set is A:{1,2} I want to have {}, {1}, {2}, {1,2}例如,如果我的集合是A:{1,2}我想要{}, {1}, {2}, {1,2}

this is what I tried:这是我尝试过的:

    static void printSubsets(java.util.Set<Integer> a) {
            int n = a.size();
            // Run a loop for printing all 2^n
            // subset one by one
            for (int i = 0; i < (1 << n); i++) {
                System.out.print("{");
                // Print current subset
                for (int j = 0; j < n; j++) {
    
                    // (1<<j) is a number with jth bit 1
                    // so when we 'and' them with the
                    // subset number we get which numbers
                    // are present in the subset and which
                    // are not
                    if ((i & (1 << j)) > 0)
                        System.out.print(a.toArray()[j] + ",");
                    if (j == n - 1)
                       System.out.print(a.toArray()[j]);
                }
                System.out.print("} , ");
            }
        }

and this is the out put {}, {1,}, {2,}, {1,2,}, my problem is with , .这是输出{}, {1,}, {2,}, {1,2,},我的问题是, I do not want to have , at the end of every subset and at the end of the whole output.我不想在每个子集,末尾和整个 output 的末尾都有。 Can you help me solve this problem to have a output like {}, {1}, {2}, {1,2} ?你能帮我解决这个问题,得到一个像{}, {1}, {2}, {1,2}这样的 output 吗? and at the end i want to sort them最后我想对它们进行排序

If you are allow to use Guava you can take advantage of its Sets class and Sets.combinations(Set<E> set, int size) method:如果你被允许使用Guava ,你可以利用它的Sets class 和Sets.combinations(Set<E> set, int size)方法:

static void printSubsets(Set<Integer> a) {

    String combinations = IntStream.rangeClosed(0, a.size()).boxed()
            .flatMap(i -> Sets.combinations(a, i).stream()
                                    .sorted(Comparator.comparingInt(Collections::max)))
            .map(subSet -> subSet.stream().sorted().map(String::valueOf)
                                    .collect(Collectors.joining(",", "{", "}")))
            .collect(Collectors.joining(" , "));

    System.out.println(combinations);
}

Then:然后:

Set<Integer> set = Set.of(1, 2);

printSubsets(set);

Output: Output:

{} , {1} , {2} , {1,2}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM