Day 7: Spearman's Rank Correlation Coefficient

  • + 0 comments

    c# version

        static void Main(String[] args) {
            System.Console.ReadLine();
            var xs = System.Console.ReadLine();
            var ys = System.Console.ReadLine();
            System.Console.WriteLine(
                SpearmanRank(ToArr(xs), ToArr(ys)).ToString("f3")
            );
        }
    
        static double[] ToArr(string xs)
        {
            var zs = xs.Trim().Split(' ');
            int l = zs.Length;
            var arr = new double[l];
            int i = -1;
            while(++i<l){
                arr[i] = double.Parse(zs[i]);
            }
            return arr;
        }
    
        static double SpearmanRank(double[] xs, double[] ys)
        {
            var rxs = GetRank(xs);
            var rys = GetRank(ys);
            
            int n = xs.Length;
            double r = 0;
            for(int i=0;i<n;i++)
            {
                r += Math.Pow(rxs[i] - rys[i], 2);
            }
            
            return 1.0 - (6 * r) / (n * ( Math.Pow(n, 2) - 1 ));
        }
    
        static double[] GetRank(double[] xs)
        {
            int n = xs.Length;
            var dic = new SortedDictionary<double, List<int>>();
            for(int i=0;i<n;i++)
            {
                var x = xs[i];
                List<int> ps;
                if (!dic.TryGetValue(x, out ps))
                {
                    ps = new List<int>();
                    dic.Add(x, ps);
                }
                ps.Add(i);
            }
            var rnks = new double[n];
            int p = 1;
            foreach(var d in dic)
            {
                var ws = d.Value;
                foreach(var w in ws)
                {
                    rnks[w] = p;
                }
                p++;
            }
            return rnks;
        }