วันอาทิตย์ที่ 2 พฤศจิกายน พ.ศ. 2557

Lab 5 - class Matrix

void setup(){
  int[][] a = {{-1,2,1},
               {3,-2,4},
               {2,-3,1}};
  int[][] b = {{7,4,-2},
               {-1,-5,1},
               {-3,4,6}};
  Matrix m = new Matrix(a);
  Matrix n = new Matrix(b);
  m.ChangeValueAt(4,2,2);
  m.ShowMatrix();
  m.AddMatrix(n);
  m.ShowMatrix();
  n.SubMatrix(m);
  n.ShowMatrix();
}

class Matrix{
  int[][] matrix;
  int max_row;
  int max_column;
  Matrix(int r,int c){
    matrix = new int[r][c];
    this.max_row = this.matrix.length;
    this.max_column = this.matrix[0].length;
  }
  Matrix(int[][] a){
    this.matrix = a;
    this.max_row = this.matrix.length;
    this.max_column = this.matrix[0].length;
  }
  void ChangeMatrix(int[][] a){
    this.matrix = a;
    this.max_row = this.matrix.length;
    this.max_column = this.matrix[0].length;
  }
  void ChangeValueAt(int value,int r,int c){
    this.matrix[r-1][c-1] = value;
  }
  void ShowMatrix(){
    for(int r=0;r<this.max_row;r++){
      print("|");
      for(int c=0;c<this.max_column;c++){
        if(this.matrix[r][c]>=0){
          print("  "+this.matrix[r][c]+" ");
        }
        else print(" "+this.matrix[r][c]+" ");
      }
      println("|");
    }
    println("");
  }
  void AddMatrix(Matrix x){
    if((this.max_row==x.max_row)&&(this.max_column==x.max_column)){
      for(int r=0;r<this.max_row;r++){
        for(int c=0;c<this.max_column;c++){
          this.matrix[r][c] = this.matrix[r][c] + x.matrix[r][c];
        }
      }
    }
    else println("Can't add matrix");
  }
  void SubMatrix(Matrix x){
    if((this.max_row==x.max_row)&&(this.max_column==x.max_column)){
      for(int r=0;r<this.max_row;r++){
        for(int c=0;c<this.max_column;c++){
          this.matrix[r][c] = this.matrix[r][c] - x.matrix[r][c];
        }
      }
    }
    else println("Can't subtract matrix");
  }
  /*
  int FindDet(){
    int det=0;
    if((this.max_row==this.max_column) ){
      if(this.max_row==2){
        det = (this.matrix[0][0]*this.matrix[1][1])-(this.matrix[1][0]*this.matrix[0][1]);
      }
      else {
        if(this.max_row==3){
          for(int c=0;c<this.matrix[0].length;c++){
            for(int r=c
          }
        }
        else {
          println("Can't find determinant");
        }
      }
    }
    else println("Can't find determinant");
    return det;
  }
  */
}