File tree Expand file tree Collapse file tree
src/main/java/lambdasinaction/chap12 Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package lambdasinaction.chap12;
2+
3+ import java.util.stream.LongStream;
4+
5+ /**
6+ * Created by raoul-gabrielurma on 16/05/2014.
7+ */
8+ public class Recursion {
9+
10+ public static void main(String[] args) {
11+ System.out.println(factorialIterative(5));
12+ System.out.println(factorialRecursive(5));
13+ System.out.println(factorialStreams(5));
14+ System.out.println(factorialTailRecursive(5));
15+ }
16+
17+ public static int factorialIterative(int n) {
18+ int r = 1;
19+ for (int i = 1; i <= n; i++) {
20+ r*=i;
21+ }
22+ return r;
23+ }
24+
25+ public static long factorialRecursive(long n) {
26+ return n == 1 ? 1 : n*factorialRecursive(n-1);
27+ }
28+
29+ public static long factorialStreams(long n){
30+ return LongStream.rangeClosed(1, n)
31+ .reduce(1, (long a, long b) -> a * b);
32+ }
33+
34+ public static long factorialTailRecursive(long n) {
35+ return factorialHelper(1, n);
36+ }
37+
38+ public static long factorialHelper(long acc, long n) {
39+ return n == 1 ? acc : factorialHelper(acc * n, n-1);
40+ }
41+ }
Original file line number Diff line number Diff line change 1+ package lambdasinaction.chap12;
2+
3+ import java.util.ArrayList;
4+ import java.util.Arrays;
5+ import java.util.Collections;
6+ import java.util.List;
7+
8+ /**
9+ * Created by raoul-gabrielurma on 16/05/2014.
10+ */
11+ public class SubsetsMain {
12+
13+ public static void main(String[] args) {
14+ List<List<Integer>> subs = subsets(Arrays.asList(1, 4, 9));
15+
16+ subs.forEach(System.out::println);
17+
18+ }
19+
20+
21+ public static List<List<Integer>> subsets(List<Integer> l) {
22+ if (l.isEmpty()) {
23+ List<List<Integer>> ans = new ArrayList<>();
24+ ans.add(Collections.emptyList());
25+ return ans;
26+ }
27+ Integer first = l.get(0);
28+ List<Integer> rest = l.subList(1,l.size());
29+ List<List<Integer>> subans = subsets(rest);
30+ List<List<Integer>> subans2 = insertAll(first, subans);
31+ return concat(subans, subans2);
32+ }
33+
34+ public static List<List<Integer>> insertAll(Integer first, List<List<Integer>> lists) {
35+ List<List<Integer>> result = new ArrayList<>(); for (List<Integer> l : lists) {
36+ List<Integer> copyList = new ArrayList<>(l);
37+ copyList.add(first);
38+ result.add(copyList);
39+ }
40+ return result;
41+ }
42+
43+ static List<List<Integer>> concat(List<List<Integer>> a, List<List<Integer>> b) {
44+ List<List<Integer>> r = new ArrayList<>(a);
45+ r.addAll(b);
46+ return r;
47+ }
48+ }
You can’t perform that action at this time.
0 commit comments