Day 7: Spearman's Rank Correlation Coefficient

  • + 0 comments

    C++

    #include <cmath>
    #include <cstdio>
    #include <vector>
    #include <iostream>
    #include <algorithm>
    #include <iomanip>
    using namespace std;
    
    int getIndexOf(double a, vector<double> y)
    {
        int count=1;
        for (int j=0; j<y.size(); ++j)
        {
            if (a==y[j])
                break;
            else
                count++;
        }
        return count;
    }
    
    vector<int> getRank(vector<double> x)
    {
        vector<int> xVar(x.size());
        vector<double> x_sorted(x.size());
        partial_sort_copy(begin(x), end(x), begin(x_sorted), end(x_sorted));
        for(int i=0; i<x.size(); ++i)
        {
            int index=getIndexOf(x[i], x_sorted);
            xVar[i]=index;
        }
        return xVar;
    }
    
    int main() {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
        int n;
        cin>>n;
        
        vector<double> x,y;
        double num=0;
        for(int i=0; i<n; ++i){
            cin>>num;
            x.push_back(num);
        }
        
        for(int i=0; i<n; ++i){
            cin>>num;
            y.push_back(num);
        }
        vector<int> rankX=getRank(x);
        vector<int> rankY=getRank(y);
        
        double r=0;
        for (int i=0; i<n; ++i)
        {
            r+=pow((rankX[i]-rankY[i]),2.);
        }
        cout<<fixed<<setprecision(3);
        cout<<1-6*r/(n*n*n-n);
        return 0;
    }