dpaukov / combinatoricslib3

Combinatorial objects stream generators for Java.
Apache License 2.0
177 stars 24 forks source link

Subsets - give all subsets containing exactly n elements. #12

Closed axkr closed 2 years ago

axkr commented 3 years ago

Is there an implementation for subsets containing exactly n elements.?

This can of course be done with the stream() API, but I assume it will be faster, if its already implemented in the subset iterator itself.

In case you provide an implementation, the ordering of subsets should also be adjusted.

Instead of this ordering in your example:

   []
   [one]
   [two]
   [one, two]
   [three]
   [one, three]
   [two, three]
   [one, two, three]

It should be ordered like this IMO:

   []
   [one]
   [two]
   [three]
   [one, two]
   [one, three]
   [two, three]
   [one, two, three]
dpaukov commented 2 years ago

If you need all subsets containing exactly n elements, you can use the simple combination generator Generator.combination(array).simple(n). The similar approach can be used for generating all subsets in ascending order of their size (number of elements):

static <T> void exactSizeSubSet(T[] arr, int n) {
      assert(n >= 0);
      assert(n <= arr.length);
      Generator.combination(arr)
             .simple(n)
             .stream()
             .forEach(System.out::println);
}

static <T> void allOrderedSubSets(T[] arr) {
     IntStream.rangeClosed(0, arr.length)
         .forEach(i -> Generator.combination(arr)
             .simple(i)
             .stream()
             .forEach(System.out::println));
}
dpaukov commented 2 years ago

I assume I can close this issue.