-
Notifications
You must be signed in to change notification settings - Fork 33
/
Problem_08.java
62 lines (57 loc) · 1.48 KB
/
Problem_08.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* Cracking-The-Coding-Interview
* Problem_08.java
*/
package com.deepak.ctci.Ch13_Java;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* <br> Problem Statement:
*
* Using lambda expressions, write a function
* "List<Integer> getRandomSubset(List<Integer> list)"
* that returns a random subset of arbitrary size.
* All subsets including the empty subset are likely
* equally to be chosen.
*
* </br>
*
* @author Deepak
*/
public class Problem_08 {
/**
* Method to get random subset using advanced java loop
* NOTE : We will use random to solve this problem. There can be other better ways
*
* @param list
* @return {@link List<Integer>}
*/
public static List<Integer> getRandomSubsetUsingLoop(List<Integer> list) {
List<Integer> randomSubset = new ArrayList<>();
Random random = new Random();
for (Integer item : list) {
if (random.nextBoolean()) {
randomSubset.add(item);
}
}
return randomSubset;
}
/**
* Method to get random subset using lambda
*
* @param list
* @return {@link List<Integer>}
*/
public static List<Integer> getRandomSubsetUsingLambda(List<Integer> list) {
List<Integer> randomSubset = new ArrayList<>();
Random random = new Random();
Predicate<Object> flipCoin = o -> {
return random.nextBoolean();
};
randomSubset = list.stream().filter(flipCoin).collect(Collectors.toList());
return randomSubset;
}
}