-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Solution.java
63 lines (55 loc) · 1.7 KB
/
Solution.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
// github.com/RodneyShag
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
/* Save input */
Scanner scan = new Scanner(System.in);
int size = scan.nextInt();
double [] xs = new double[size];
double [] ys = new double[size];
for (int i = 0; i < size; i++) {
xs[i] = scan.nextDouble();
}
for (int i = 0; i < size; i++) {
ys[i] = scan.nextDouble();
}
scan.close();
System.out.println(pearson(xs, ys));
}
/* Calculates Pearson coefficient */
private static Double pearson(double [] xs, double [] ys) {
if (xs == null || ys == null || xs.length != ys.length) {
return null;
}
double xMean = getMean(xs);
double yMean = getMean(xs);
int n = xs.length;
double numerator = 0;
for (int i = 0; i < n; i++) {
numerator += (xs[i] - xMean) * (ys[i] - yMean);
}
return numerator / (n * standardDeviation(xs) * standardDeviation(ys));
}
private static Double getMean(double [] array) {
if (array == null) {
return null;
}
double total = 0;
for (double num : array) {
total += num;
}
return total / array.length;
}
private static Double standardDeviation(double [] array) {
if (array == null) {
return null;
}
double mean = getMean(array);
double sum = 0;
for (double x : array) {
sum += Math.pow(x - mean, 2);
}
double variance = sum / array.length;
return Math.sqrt(variance);
}
}