-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathDouble.java
More file actions
90 lines (84 loc) · 2.28 KB
/
Double.java
File metadata and controls
90 lines (84 loc) · 2.28 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
package control;
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;
public class Double {
/**
* Sums all values squared from 0 to n
*
* @param n The number of natural numbers to sum.
* @return The sum of the first n natural numbers squared.
*/
public static int sumSquare(int n) {
// Using the mathematical formula n(n+1)(2n+1)/6 for sum of squares
return n * (n + 1) * (2 * n + 1) / 6;
}
/**
* Sums all triangular numbers from T(1) to T(n)
*
* @param n The number of triangular numbers to sum.
* @return The sum of the first n triangular numbers.
*/
public static int sumTriangle(int n) {
// Using the mathematical formula n(n+1)(n+2)/6 for sum of triangular numbers
return n * (n + 1) * (n + 2) / 6;
}
/**
* Counts the number of pairs in an array
*
* A pair is any value that is repeated exactly twice in the array.
*
* @param arr The array of integers.
* @return The number of pairs in the array.
*/
public static int countPairs(int[] arr) {
Map<Integer, Integer> counts = new HashMap<>();
for (int value : arr) {
counts.put(value, counts.getOrDefault(value, 0) + 1);
}
int pairs = 0;
for (int count : counts.values()) {
if (count == 2) {
pairs++;
}
}
return pairs;
}
/**
* Counts the number of instances where the values at the same index are equal
*
* @param arr0 The first array of integers.
* @param arr1 The second array of integers.
* @return The number of instances where the values at the same index are
* equal.
*/
public static int countDuplicates(int[] arr0, int[] arr1) {
if (arr0 == null || arr1 == null) {
return 0;
}
int count = 0;
int minLength = Math.min(arr0.length, arr1.length);
for (int i = 0; i < minLength; i++) {
if (arr0[i] == arr1[i]) {
count++;
}
}
return count;
}
/**
* Sums all values in a 2D array
*
* note: dimensions must be equal
*
* @param arr The 2D array of integers.
* @return The sum of all values in the 2D array.
*/
public static int sumMatrix(int[][] arr) {
if (arr == null || arr.length == 0) {
return 0;
}
return Arrays.stream(arr)
.flatMapToInt(Arrays::stream)
.sum();
}
}