using System;
using System.Collections.Generic;
using System.Linq;

namespace FullScreenShaders.Structure
{
    static class Statistics
    {
        public static double Variance(this IEnumerable<double> x)
        {
            double xBar = x.Average();
            int n = x.Count();

            return x.Sum(xi => Math.Pow(xi - xBar, 2)) / n;
        }

        public static double StandardDeviation(this IEnumerable<double> x)
        {
            return Math.Sqrt(x.Variance());
        }

        public static double Covariance(this IEnumerable<double> x, IEnumerable<double> y)
        {
            double xBar = x.Average(), yBar = y.Average();
            int n = x.Count();

            double sum = 0;
            for (int i = 0; i < n; i++)
                sum += (x.ElementAt(i) - xBar) * (y.ElementAt(i) - yBar);

            return sum / n;
        }

        public static double Correlation(this IEnumerable<double> x, IEnumerable<double> y)
        {
            double sxy = x.Covariance(y);
            double sx = x.StandardDeviation(), sy = y.StandardDeviation();

            return sxy / (sx * sy);
        }
    }
}
