import java.io.*;

class NA17
{ public static double[][] C(double a[][],double b[])
  {int n=a.length;int m=a[0].length;double c[][]=new double[n][m+1];
  for(int i=0;i<n;i++){for(int j=0;j<m;j++){c[i][j]=a[i][j];};c[i][m]=b[i];}
  return c;
  }
  
  public static double[][] C(double a[][],double b[][])
  {int n=a.length;int o=b[0].length;int m=n+o;double c[][]=new double[n][m];
  for(int i=0;i<n;i++)
  {for(int j=0;j<n;j++){c[i][j]=a[i][j];};
   for(int j=n;j<m;j++){c[i][j]=b[i][j];}
  }
  return c;
  }
  
  public static double[][] gaussjordanwithpivot(double a[][])
  { //pivotlu
  int n=a.length;
  int m=a[0].length;	  
  int o=m-n;
  double x[][]=new double[n][o];
  double carpan=0;
  double toplam=0;
  double buyuk;
  double dummy=0;
  int i,j,k,p,ii,jj;
  i=0;
  for(k=0;k<n;k++)
  { //pivoting
	p=k;
	buyuk=Math.abs(a[k][k]);
	for(ii=0;ii<n;ii++)
	{  if(i!=k)
	   {
	   dummy=Math.abs(a[ii][k]);
	   if(dummy > buyuk) {buyuk=dummy;p=ii;}
       }
	}
	if(p!=k)
	{ for(jj=k;jj<m;jj++)
	  { dummy=a[p][jj];
	    a[p][jj]=a[k][jj];
	    a[k][jj]=dummy;
	  }
	}
	//gauss jordan elimination
	for(j=k+1;j<m;j++)
	{ a[k][j]/=a[k][k]; }
	a[k][k]=1.0;	  
    for(i=0;i<n;i++)
    {  if(i!=k)
       {
	      carpan=a[i][k];
          a[i][k]=0;
          for(j=k+1;j<m;j++)
            {a[i][j]-=carpan*a[k][j]; }
       }    
	}
  }
  for(jj=0;jj<o;jj++)
  {for(i=0;i<n;i++) {x[i][jj]=a[i][n+jj];}}
  return x;
  } 	
  public static double[] gaussjordan(double a[][],double b[])
  {double c[][]=C(a,b);
   double d[][]=gaussjordanwithpivot(c);
   return d[0];
  }
        
  public static void main(String args[]) throws IOException
  {
  double a[][]={{1,-1,2,-1,-8},{2,-2,3,-3,-20},{1,1,1,0,-2},{1,-1,4,3,4}};
  //double b[]={-8,-20,-2,4};
  //double a[][]={{3,0,2,8},{0,0,2,-7},{6,2,8,26}};
  //double a[][]=Text.readDouble_Table();
  double x[][]=gaussjordanwithpivot(a);
  Text.print(x,"Gauss Jordan elimination with partial pivoting");
  }
}
