728x90
반응형
코드 :
using System;
namespace matrixNamespace {
// Matrix 클래스
class Matrix {
//열과 행 변수
int row;
int column;
// 행렬 변수 (가변 배열로 이루어져있다)
int[][] matrix;
//생성자 (매개변수가 없는 것)
public Matrix() {
Console.WriteLine("Matrix Create...");
Console.Write("input the Row, Column (ex. 3 3) : ");
string input = Console.ReadLine();
string[] row_column = input.Split(' ');
// 행과 열을 입력받아 인스턴스 변수에 할당한다.
this.row = Convert.ToInt32(row_column[0]);
this.column = Convert.ToInt32(row_column[1]);
//가변 배열 생성
matrix = new int[row][];
//행렬을 입력받는 메소드인 makeMatrix를 실행한다.
makeMatrix();
}
//생성자 (매개변수가 있는 것)
public Matrix(int row, int column) {
this.row = row;
this.column = column;
matrix = new int[row][];
for(int i = 0; i < row; i++) {
matrix[i] = new int[column];
}
}
//행렬 만드는 메서드
public void makeMatrix() {
for(int i = 0; i < this.matrix.Length; i++) {
Console.Write("input the columns (ex.1 2 3) : ");
string line = Console.ReadLine();
string[] columns = line.Split(' ');
int[] columnsInt = new int[columns.Length];
for (int j = 0; j < columns.Length; j++) {
columnsInt[j] = Convert.ToInt32(columns[j]);
}
matrix[i] = columnsInt;
}
}
//행렬을 출력하는 메서드
public void printMatrix() {
for(int i = 0; i < matrix.Length; i++) {
for(int j = 0; j < matrix[i].Length; j++) {
Console.Write($"{this.matrix[i][j]} ");
}
Console.Write("\n");
}
Console.Write("\n");
}
//행렬 곱셈 메서드
static public Matrix Multiplex(Matrix m1, Matrix m2) {
//if(m1.row != m2.column) return;
Matrix res = new Matrix(m1.row,m1.column);
for(int i = 0; i < m1.row; i++) {
for(int j = 0; j < m1.column; j++) {
for(int k = 0; k < m1.column; k++) {
res.matrix[i][j] += m1.matrix[i][k] * m2.matrix[k][j];
}
}
}
return res;
}
// 같은 열과 행에 관해서만 현재 계산이 됩니다.
// 행렬 더하기, 빼기 메서드, 대리자를 이용하여 함축화하였다.
static public Matrix calculator(Matrix m1, Matrix m2, calculate cal) {
Matrix res = new Matrix(m1.row, m1.column);
try {
for(int i = 0; i < m1.row; i++) {
for(int j = 0; j < m1.column; j++) {
res.matrix[i][j] = cal(m1.matrix[i][j],m2.matrix[i][j]);
}
}
} catch(IndexOutOfRangeException e) {
Console.WriteLine("Index Out Error!");
}
return res;
}
//대리자를 위한 메서드이다.
public static int Plus(int a, int b) { return a + b; }
public static int Minus(int a, int b) { return a - b; }
}
//대리자 calculate
delegate int calculate(int a, int b);
class matrixCode {
static void Main() {
Matrix m1 = new Matrix();
Matrix m2 = new Matrix();
m1.printMatrix();
m2.printMatrix();
//더하기 연산
Matrix m3 = Matrix.calculator(m1,m2, new calculate(Matrix.Plus));
m3.printMatrix();
//빼기 연산
Matrix m4 = Matrix.calculator(m1,m2, new calculate(Matrix.Minus));
m4.printMatrix();
//곱셈 연산
Matrix m5 = Matrix.Multiplex(m1,m2);
m5.printMatrix();
}
}
}
728x90
반응형
'제작 > 기타 프로그램' 카테고리의 다른 글
[티스토리 포스팅] 프로젝트 "내일의 모든 것" (0) | 2024.09.26 |
---|---|
[카카오 채팅방 매니저][Node.js] #1 프로젝트 기획 (0) | 2022.08.09 |
[C#] 행렬 계산기 (5) - 곱셈 계산 (0) | 2020.10.21 |
[C#] 행렬 계산기 (4) - 이차원 배열로 더 간단하게 표현 (0) | 2020.10.20 |
[C#] 행렬 계산기 (3) - 대리 연산자를 활용하여 함축화 (0) | 2020.10.15 |