Kamis, 02 Juni 2011

Program Hitung Determinan Matrik Ordo 2×2, 3×3 dan 4×4 Dengan Java

import java.io.*;
import java.math.*;

public class determinan {
    public static void getDeterminan(int d) throws IOException{
        int a[][] = new int[d][d];
        double result;
         read(a, d);
         print(a, d);
         result = determinan(a, d);
        System.out.println("Hasil matriks diatas adalah : "+result);
    }

    public static void read(int b[][], int m) throws IOException{
        DataInputStream input = new DataInputStream(System.in);
         for(int i=0;i<m;i++){
              for(int j=0;j<m;j++){
                  System.out.print("Elemen ke ["+(i+1)+","+(j+1)+"]"+" : ");
                  b[i][j] = Integer.parseInt(input.readLine());
              }
         }
    }

    public static void print(int b[][], int m){
         for(int i=0;i<m;i++){
              System.out.print(" ");
              for(int j=0;j<m;j++)
                System.out.print(b[i][j]+" ");
            System.out.print("\n");
         }
    }

    public static double determinan(int b[][], int m){
         int i,j, c[][] = new int[5][5];
         double sum = 0;
         if(m==2){
            sum = b[0][0]*b[1][1] - b[0][1]*b[1][0];
            return sum;
          }
         for(int p=0;p<m;p++){
              int h = 0,k = 0;
              for(i=1;i<m;i++){
                for(j=0;j<m;j++){
                     if(j==p)
                          continue;
                     c[h][k] = b[i][j];
                     k++;
                     if(k == m-1){
                         h++;
                         k = 0;
                      }
                }
              }
              sum = sum + b[0][p] * Math.pow(-1,p) * determinan(c,(m-1));
         }
         return sum;
    }
   
    public static void main(String[]args) throws IOException{
        DataInputStream inputs = new DataInputStream(System.in);
        int kode = 0;
        System.out.println("1. Matriks Ordo 2x2");
        System.out.println("2. Matriks Ordo 3x3");
        System.out.println("3. Matriks Ordo 4x4");
        System.out.println("-------------------");
        System.out.print("Masukkan kode (1/2/3) : ");
        kode = Integer.parseInt(inputs.readLine());
        if(kode==1){
            getDeterminan(2);
        }else if(kode==2){
            getDeterminan(3);
        }else if(kode==3){
            getDeterminan(4);
        }else{
            System.exit(0);
        }   
    }
}

Tidak ada komentar:

Posting Komentar