Day 7: Spearman’s Rank Correlation Coefficient | 10 Days Of Statistics | HackerRank Solution

Hello coders, today we are going to solve Day 7: Spearman’s Rank Correlation Coefficient HackerRank Solution which is a Part of 10 Days of Statistics Series.

Day 7: Spearman's Rank Correlation Coefficient

Objective

In this challenge, we practice calculating Spearman’s rank correlation coefficient.

Task

Given two n-element data sets, X and Y, calculate the value of Spearman’s rank correlation coefficient.

Input Format

The first line contains an integer, n, denoting the number of values in data sets X and Y.
The second line contains n space-separated real numbers (scaled to at most one decimal place) denoting data set X.
The third line contains n space-separated real numbers (scaled to at most one decimal place) denoting data set Y.

Constraints

  • 10 <= n <= 100
  • 1 <= xi <= 500, where xi is the ith value of data set X.
  • 1 <= yi <= 500, where yi is the ith value of data set Y.
  • Data set X contains unique values.
  • Data set Y contains unique values.

Output Format

Print the value of the Spearman’s rank correlation coefficient, rounded to a scale of 3 decimal places.

Sample Input

10
10 9.8 8 7.8 7.7 1.7 6 5 1.4 2 
200 44 32 24 22 17 15 12 8 4

Sample Output

0.903

Solution – Spearman’s Rank Correlation Coefficient

C++

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


/*
    rank = 1 - (6*summation(x[i]-y[i])^2)/n*(n^2-1);
*/

vector<double> build_rank(double x[], int n)
{
    map<double, int> m1;
    vector<double> x1(n);
    
    for(auto i=0; i<n; i++) 
    {
        m1.insert(make_pair(x[i], i));
    }
    
    int rank = 0;
    for(auto it : m1)
    {
        x1[it.second] = rank++;
    }
    
    return x1;
}
double supermans_rank(double x[], double y[], int n)
{       
    double num = 0;
    
    auto rank_x = build_rank(x, n);
    auto rank_y = build_rank(y, n);
    
    for(auto i=0; i<n; i++)
    {
        num += ((rank_x[i]-rank_y[i])*(rank_x[i]-rank_y[i]));
    }
    num *= 6.0;
    
    double den = (n*(n*n - 1));
    
    double res = num/den;
    
    res = 1 - res;
    
    return res;    
}

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    
    int n; cin>>n; double x[n+4], y[n+4];
    
    for(auto i=0; i<n; i++)
    {
        cin>>x[i];
        //sum1 += x[i];
    }
    
    for(auto i=0; i<n; i++)
    {
        cin>>y[i];
        //sum3 += y[i];
    }
    
    double supermans_rank_coeff = supermans_rank(x, y, n);
    
    printf("%0.3f", supermans_rank_coeff);

    
    return 0;
}

Disclaimer: The above Problem (Spearman’s Rank Correlation Coefficient) 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 *