Source : https://www.hackerrank.com/challenges/s10-least-square-regression-line
Objective
In this challenge, we practice using linear regression techniques. Check out the Tutorial tab for learning materials!
Task
A group of five students enrolls in Statistics immediately after taking a Math aptitude test. Each student's Math aptitude test score, , and Statistics course grade, , can be expressed as the following list of points:
If a student scored an on the Math aptitude test, what grade would we expect them to achieve in Statistics? Determine the equation of the best-fit line using the least squares method, then compute and print the value of when .
Input Format
There are five lines of input; each line contains two space-separated integers describing a student's respective and grades:
95 85
85 95
80 70
70 65
60 70
If you do not wish to read this information from stdin, you can hard-code it into your program.
Output Format
Print a single line denoting the answer, rounded to a scale of decimal places (i.e., format).
Source : https://www.hackerrank.com/challenges/s10-least-square-regression-line
Solution
// Karthikalapati.blogspot.com | |
import java.util.Scanner; | |
public class Solution { | |
public static void main(String[] args) { | |
/* Hardcoded data */ | |
int [] x = {95, 85, 80, 70, 60}; | |
int [] y = {85, 95, 70, 65, 70}; | |
double studentScore = 80; | |
/* Get coefficients for Least Square Regression Line */ | |
double b = pearson(x, y) * (standardDeviation(y) / standardDeviation(x)); | |
double a = getMean(y) - b * getMean(x); | |
/* Calculate and print predicted score */ | |
double result = a + b * studentScore; | |
System.out.format("%.3f", result); | |
} | |
/* Calculates Pearson coefficient */ | |
private static Double pearson(int [] xs, int [] 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(int [] array) { | |
if (array == null) { | |
return null; | |
} | |
int total = 0; | |
for (int num : array) { | |
total += num; | |
} | |
return (double) total / array.length; | |
} | |
private static Double standardDeviation(int [] array) { | |
if (array == null) { | |
return null; | |
} | |
double mean = getMean(array); | |
int sum = 0; | |
for (double x : array) { | |
sum += Math.pow(x - mean, 2); | |
} | |
double variance = sum / array.length; | |
return Math.sqrt(variance); | |
} | |
} |
No comments:
Post a Comment