In this Hackerrank Day 7: Spearman's Rank Correlation Coefficient I 10 Days of Statistics problem You have given two n-element data sets, X and Y, to calculate the value of Spearman's rank correlation coefficient.

HackerRank Day 7: Spearman's Rank Correlation Coefficient | 10 Days of Statistics solution


Problem solution in Python programming.

# Enter your code here. Read input from STDIN. Print output to STDOUT
def get_rank(X, n):
    x_rank = dict((x, i+1) for i, x in enumerate(sorted(set(X))))
    return [x_rank[x] for x in X]
    
n = int(input())
X = list(map(float, input().split()))
Y = list(map(float, input().split()))

rx = get_rank(X, n)
ry = get_rank(Y, n)

d = [(rx[i] -ry[i])**2 for i in range(n)]
rxy = 1 - (6 * sum(d)) / (n * (n*n - 1))

print('%.3f' % rxy)



Problem solution in Java Programming.

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        double[] x = new double[n];
        double[] y = new double[n];
        double[] x2 = new double[n];
        double[] y2 = new double[n];
        
        for (int i = 0; i<n; i++) {
            x[i] = scanner.nextDouble();
            x2[i] = x[i];
            
        }
        for (int i = 0; i<n; i++) {
            y[i] = scanner.nextDouble();  
            y2[i] = y[i];  

        }
        scanner.close();
        
        Arrays.sort(x2);
        Arrays.sort(y2);

        int sum = 0;
        for (int i =0; i<n; i++) {
            sum += Math.pow((double)(getRank(x[i], x2) - getRank(y[i],y2)),2);
        }
        
        double result = 1.0 - (6.0*sum)/(n*(n*n-1));
        System.out.println(String.format("%.3f",result));
    }
    
    private static int getRank(double item, double[] a) {
        for (int i = 0; i< a.length; i++) {
            if(item == a[i]) 
                return i+1;
        } 
        return -1;
    }
}


Problem solution in C++ programming.

#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>

using namespace std;

vector<int> ranks(vector<double> x) {
    vector<pair<double, int>> v;
    
    int n = static_cast<int>(x.size());
    
    for (int i = 0; i < n; i++) {
        v.push_back({x[i], i});
    }
    
    sort(begin(v), end(v));
    
    vector<int> r(n);
    
    for (int i = 0; i < n; i++) {
        r[v[i].second] = i + 1;
    }
    
    return r;
}

double spearman(vector<double> x, vector<double> y) {
    vector<int> rx = ranks(x);
    vector<int> ry = ranks(y);
    
    int n = static_cast<int>(x.size());
    
    double s = 0;
    
    for (int i = 0; i < n; i++) {
        s += (rx[i] - ry[i]) * (rx[i] - ry[i]);
    }
    
    double c = (6 * s) / (n * (n * n - 1.0));
    
    return 1.0 - c;
}

int main() {
    int n;
    cin >> n;
    
    vector<double> x(n);
    
    for (int i = 0; i < n; i++) {
        cin >> x[i];
    }
    
    vector<double> y(n);
    
    for (int i = 0; i < n; i++) {
        cin >> y[i];
    }
    
    cout << setprecision(3) << fixed << spearman(x, y);
    
    return 0;
}


Problem solution in C programming.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int n;
    scanf("%d",&n);
    double a[n],b[n];
    for(int i=0;i<n;i++)
        scanf("%lf", &a[i]);
    for(int i=0;i<n;i++)
        scanf("%lf", &b[i]);
    
    int ra[n],rb[n];
    for(int i=0;i<n;i++){
        ra[i]=1;
        rb[i]=1;
        for(int j=0;j<i;j++){
            if(a[j]<a[i])
                ra[i]++;
            else
                ra[j]++;
            
            if(b[j]<b[i])
                rb[i]++;
            else
                rb[j]++;
        }
    }
    
    double rs=0;
    for(int i=0;i<n;i++){
        rs += (ra[i]-rb[i])*(ra[i]-rb[i]);
    }
    rs = 1-6*rs/n/(n*n-1);
    printf("%.3lf", rs);
    return 0;
}


Problem solution in JavaScript programming.

function processData(input) {
    //Enter your code here
    input = input.split("\n");
    let x = input[1].trim().split(" ").map((a) => Number(a));
    let y = input[2].trim().split(" ").map((a) => Number(a));

    function spearman(x, y) {
        // slice used to copy the array
        let xsort = x.slice().sort((a, b) => a - b);
        let ysort = y.slice().sort((a, b) => a - b);

        let res = 0;

        for (let i = 0; i < xsort.length; i++){
            let n1 = xsort.indexOf(x[i]) + 1;
            let n2 = ysort.indexOf(y[i]) + 1;

            res += (n1 - n2)**2
        }
        
        return 1 - ((6*res) / (x.length * (x.length**2)));

    }
    
    let res = spearman(x, y);
    console.log(res.toFixed(3));
}   

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});