using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _03_2_Aproksymacja
{
  public class Poli
  {
    //liczba punktów
    public int n;
    //stopień wielomianu
    public int m;
    //punkty (x,y)
    public double[] x;
    public double[] y;
    //macierz...
    public double[,] A;
    //wektor wyrazów wolnych
    public double[] b;
    //współczynniki wielomianu 
    public double[] a;

    public double PoliczDlaX(double x0)
    {
      double sum = 0;
      double rx = 1;
      for (int i = 0; i <= m; i++)
      {
        sum = sum + a[i] * rx;
        rx = rx * x0;
      }
      return sum;
    }

    public void Oblicz_a()
    {      
      A = new double[m + 1, m + 1];
      b = new double[m + 1];
      double[] rx = new double[n];
      double[] ry = new double[n];
      for (int k = 0; k < n; k++)
      {
        rx[k] = 1;
        ry[k] = y[k];
      }
      for (int j = 0; j <= m; j++)
      {
        int i = 0;
        double suma = 0;
        double sumaB = 0;
        for (int k = 0; k < n; k++)
        {
          suma = suma + rx[k];
          sumaB = sumaB + ry[k] * rx[k];
        }
        A[i, j] = suma;
        b[j] = sumaB;

        int i2 = i;
        int j2 = j;
        while ((j2 - 1) >= 0)
        {
          i2 = i2 + 1;
          j2 = j2 - 1;
          A[i2, j2] = suma;
        }
        for (int k = 0; k < n; k++)
          rx[k] = rx[k] * x[k];
      }

      for (int i = 1; i <= m; i++)
      {
        int j = m;
        double suma = 0;
        for (int k = 0; k < n; k++)
          suma = suma + rx[k];
        A[i, j] = suma;
        int i2 = i;
        int j2 = j;
        while ((i2 + 1) <= m)
        {
          i2 = i2 + 1;
          j2 = j2 - 1;
          A[i2, j2] = suma;
        }
        for (int k = 0; k < n; k++)
          rx[k] = rx[k] * x[k];
      }

      Matrix<double> Am = DenseMatrix.OfArray(A);
      Vector<double> bm = DenseVector.OfArray(b);
      Vector<double> am = Am.Solve(bm);
      a = am.AsArray();
    }

  }
}
