Day 8: Least Square Regression Line | 10 Days Of Statistics | HackerRank Solution

Hello coders, today we are going to solve Day 8: Least Square Regression Line HackerRank Solution which is a Part of 10 Days of Statistics Series.

Day 8: Least Square Regression Line


In this challenge, we practice using linear regression techniques. 


A group of five students enrolls in Statistics immediately after taking a Math aptitude test. Each student’s Math aptitude test score, x, and Statistics course grade, y, can be expressed as the following list of (x, y) points:

  1. (95, 85)
  2. (85, 95)
  3. (80, 70)
  4. (70, 65)
  5. (60, 70)

If a student scored an 80 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 y when x = 80.

Input Format

There are five lines of input; each line contains two space-separated integers describing a student’s respective x and y 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 3 decimal places (i.e., 1.234 format).

Solution – Least Square Regression Line


#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

double reg(vector<int>x, vector<int>y)
    // mean
    long sum1 = 0;
    for(int i=0; i<x.size(); i++)
        sum1 += x[i];
    double mean1 = (double)sum1/x.size();
    long sum2 = 0;
    for(int i=0; i<y.size(); i++)
        sum2 += y[i];
    double mean2 = (double)sum2/y.size();
    // sqre sum
    long xsq = 0;
    for(int i=0; i<x.size(); i++)
        xsq += (x[i]*x[i]);
    // sum: xy
    long xy = 0;
    for(int i=0; i<x.size(); i++)
        xy += (x[i]*y[i]);
    // finding a & b;
    double b = (5.0*xy - sum1*sum2)/(5.0*xsq - sum1*sum1);
    double a = mean2 - b*mean1;
    return a + b*80;

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
    vector<int> x,y;
    for(auto i=0; i<5; i++)
        int p, q;
    double res = reg(x, y);
    printf("%0.3f", res);
    return 0;

Disclaimer: The above Problem (Least Square Regression Line) is generated by Hacker Rank but the Solution is Provided by CodingBroz. This tutorial is only for Educational and Learning Purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *