package lt.ktu.mockus.srgm;

import java.util.Arrays;

public class Gausas
{
	static double[][] dMatr;	//Tiesines lygciu sistemos koeficientu matrica
	static double[] dMas;		//Laisvuju nariu vektorius
	static int iN;				//Kintamuju skaicius
	static double[] dX;			//Rastas sprendinio vektorius
	
	Gausas(double[][] dMatr, double[] dMas, int iN)
	{
		this.iN = iN;
		this.dMatr = dMatr;
		this.dMas = dMas;
                //System.out.println("-------------------------------------");
                //System.out.println("-------------------------------------");
                //   System.out.println( Arrays.toString( this.dMatr ) );
                //   System.out.println( this.dMatr.length );
                /*
                String output = "";
                for ( int i = 0; i < this.dMatr.length; i++ ) {
                    output = "";
                    for ( int j = 0; j < this.dMatr[i].length; j++ ) {
                        output += " " + this.dMatr[i][j];
                   }
                    //System.out.println( output );
               }*/
                

	}
	
	public static double[] eqsolve()
	{
		int i, j, max, k;
		double t;
		
		for ( i = 0; i < iN-1; i++)
		{
			for (j = i+1, max = i; j < iN; j++)		//eilutes su max abs koeficentu paieska
				if ( Math.abs(dMatr[j][i]) > Math.abs(dMatr[max][i]) ) max = j;
			
			if (dMatr[max][i]==0)
			{
				System.out.println("Lygciu sistema nesuderinta, arba labai daug sprendiniu!");
				System.exit(1);
			}
			if (max != i)	//jeigu max kita, tai sukeisti vietomis
			{
				for (k = 0; k < iN; k++)
				{
					t = dMatr[max][k]; 
					dMatr[max][k] = dMatr[i][k];
					dMatr[i][k] = t;
				}
				t = dMas[max];
				dMas[max] = dMas[i];
				dMas[i] = t;
			}
			//gauso tiesioginis kintamuju eliminavimo zingsnis
			for (j = i+1; j < iN; j++)
			{
				double s;
				s = dMatr[j][i] / dMatr[i][i];
				for (k = i; k < iN; k++)	dMatr[j][k] -= dMatr[i][k] * s;
				dMas[j] -= dMas[i] * s; 
			}
		}
		
		dX = new double[iN];
		if (dMatr[iN-1][iN-1]==0)
			{
				System.out.println("Lygciu sistema nesuderinta, arba labai daug sprendiniu!");
				System.exit(1);
			}
		//gauso atvirkstinis kintamuju eliminavi zingsnis
		for (i = iN - 1; i >= 0; i--)
		{
			dX[i] = dMas[i];
			for (j = iN - 1; j > i; j--)	dX[i] -= dMatr[i][j] * dX[j];
			dX[i] /= dMatr[i][i];
		}
		return dX;
	}
}