-
Notifications
You must be signed in to change notification settings - Fork 16
/
MeanMedianMode.java
67 lines (55 loc) · 1.79 KB
/
MeanMedianMode.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
63
64
65
66
67
package by.andd3dfx.numeric;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* @see <a href="https://youtu.be/nqalmvHE_-A">Video solution</a>
*/
public class MeanMedianMode {
public static double mean(int[] items) {
return Arrays.stream(items).sum() / (double) items.length;
}
public static double median(int[] items) {
Arrays.sort(items);
int n = items.length;
if (n % 2 == 0) {
return (items[n / 2 - 1] + items[n / 2]) / 2.0;
}
return items[n / 2];
}
public static double mode(int[] items) {
var freqMap = Arrays.stream(items)
.boxed()
.collect(Collectors.groupingBy(
i -> i, Collectors.counting()
));
int mode = items[0];
for (var key : freqMap.keySet()) {
if (Objects.equals(freqMap.get(key), freqMap.get(mode)) && key < mode) {
mode = key;
}
if (freqMap.get(key) > freqMap.get(mode)) {
mode = key;
}
}
return mode;
}
public static double quartile1(int[] items) {
var n = items.length;
int[] left = new int[n / 2];
Arrays.sort(items);
System.arraycopy(items, 0, left, 0, n / 2);
return median(left);
}
public static double quartile2(int[] items) {
return median(items);
}
public static double quartile3(int[] items) {
var n = items.length;
int[] right = new int[n / 2];
Arrays.sort(items);
int pos = (n % 2 == 0) ? (n / 2) : (n / 2 + 1);
System.arraycopy(items, pos, right, 0, n / 2);
return median(right);
}
}