-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathDouble.java
More file actions
94 lines (86 loc) · 2.1 KB
/
Double.java
File metadata and controls
94 lines (86 loc) · 2.1 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
package control;
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) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += i * i;
}
return sum;
}
/**
* 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) {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i * (i - 1) / 2;
}
return sum;
}
/**
* 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) {
int count = 0;
int[] counts = new int[1001]; // Assuming values are within 0-1000
for (int num : arr) {
counts[num]++;
}
for (int c : counts) {
if (c == 2) {
count++;
}
}
return count / 2;
}
/**
* 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) {
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) {
int sum = 0;
int n = arr.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
sum += arr[i][j];
}
}
return sum;
}
}