Java) combination / stream
Java) combination / stream
This post was migrated from Tistory. You can find the original here.
combination
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
static List<List<Integer>> combination(List<Integer> list, List<Integer> result, int depth) {
List<List<Integer>> r = new ArrayList<>();
if (result.size() == depth) {
r.add(result);
return r;
}
for (int i = 0; i < list.size(); i++) {
List<Integer> n_list = new ArrayList<>(list.stream().skip(i + 1).collect(Collectors.toList()));
List<Integer> n_result = new ArrayList<>(result.stream().collect(Collectors.toList()));
n_result.add(list.get(i));
List<List<Integer>> rr = combination(n_list, n_result, depth);
for (List<Integer> rrr : rr) {
r.add(rrr);
}
}
return r;
}
Copying a slice of the list: list.stream().skip(i + 1).collect(Collectors.toList());
This skips as many elements as skip from the front. The final conversion could be done with stream().toList(), but that’s not available on Java 8, so Collectors is used instead.
To get a list that supports add, wrap it with new ArrayList<>().
int[] -> Integer[]
1
Integer[] n_nums = Arrays.stream(nums).boxed().toArray(Integer[]::new);
I’ve posted this snippet before, but noting it again here just to keep it in mind.
list sum
1
int sum = rr.stream().mapToInt(Integer::intValue).sum();
This post is licensed under CC BY-NC 4.0 by the author.