forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMathArrays.java
More file actions
98 lines (69 loc) · 1.95 KB
/
Copy pathMathArrays.java
File metadata and controls
98 lines (69 loc) · 1.95 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package modern.challenge;
import java.util.Comparator;
public final class MathArrays {
private MathArrays() {
throw new AssertionError("Cannot be instantiated");
}
public static int maxV1(int[] arr) {
if (arr == null) {
throw new IllegalArgumentException("Array cannot be null");
}
int max = arr[0];
for (int elem : arr) {
if (elem > max) {
max = elem;
}
}
return max;
}
public static int maxV2(int[] arr) {
if (arr == null) {
throw new IllegalArgumentException("Array cannot be null");
}
int max = arr[0];
for (int elem : arr) {
max = Math.max(max, elem);
}
return max;
}
public static <T> T maxV3(T[] arr, Comparator<? super T> c) {
if (arr == null || c == null) {
throw new IllegalArgumentException("Array/Comparator cannot be null");
}
T max = arr[0];
for (T elem : arr) {
if (c.compare(elem, max) > 0) {
max = elem;
}
}
return max;
}
public static <T extends Comparable<T>> T maxV4(T[] arr) {
if (arr == null) {
throw new IllegalArgumentException("Array cannot be null");
}
T max = arr[0];
for (T elem : arr) {
if (elem.compareTo(max) > 0) {
max = elem;
}
}
return max;
}
public static double average(int[] arr) {
if (arr == null) {
throw new IllegalArgumentException("Array cannot be null");
}
return sum(arr) / arr.length;
}
public static double sum(int[] arr) {
if (arr == null) {
throw new IllegalArgumentException("Array cannot be null");
}
double sum = 0;
for (int elem : arr) {
sum += elem;
}
return sum;
}
}