Obtaining a powerset of a set in Java

后端 未结 26 1737
青春惊慌失措
青春惊慌失措 2020-11-22 11:33

The powerset of {1, 2, 3} is:

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

Let\'s say I have a Set in Java:<

26条回答
  •  花落未央
    2020-11-22 11:51

    This is my approach with lambdas.

    public static  Set> powerSet(T[] set) {
          return IntStream
                .range(0, (int) Math.pow(2, set.length))
                .parallel() //performance improvement
                .mapToObj(e -> IntStream.range(0, set.length).filter(i -> (e & (0b1 << i)) != 0).mapToObj(i -> set[i]).collect(Collectors.toSet()))
                .map(Function.identity())
                .collect(Collectors.toSet());
            }
    

    Or in parallel (see parallel() comment):

    Size of input set: 18

    Logical processors: 8 à 3.4GHz

    Performance improvement: 30%

提交回复
热议问题