Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C#에서 두 행렬이 동일한지 확인하는 방법

C#으로 두 행렬이 같은지 확인하기

두 행렬이 동일한지 판단하려면 무엇보다 먼저 두 행렬을 비교할 수 있는지 확인해야 합니다. 행렬 비교는 두 행렬의 차원, 즉 행과 열의 개수가 완전히 일치할 때에만 의미가 있기 때문입니다.

1단계: 비교 가능 여부 검사

먼저 두 행렬의 행과 열 개수가 같은지 확인합니다. 크기가 다르면 비교 자체가 불가능하므로 안내 메시지를 출력하고 비교를 진행하지 않습니다.

if (row1 != row2 || col1 != col2) {
    Console.Write("Matrices can't be compared:\n");
}

참고: 행 또는 열 중 어느 하나라도 다르면 비교할 수 없으므로, 논리 연산자는 &&(AND)가 아닌 ||(OR)을 사용해야 합니다.

2단계: 요소별 동일성 검사 (플래그 변수 활용)

크기가 같다면 이중 for 루프를 돌며 각 위치의 요소를 하나씩 비교합니다. 이때 초기값이 1인 플래그(flag) 변수를 선언하고, 서로 다른 요소를 발견하는 순간 플래그를 0으로 바꾼 뒤 break로 반복을 중단합니다.

if (row1 != row2 || col1 != col2) {
    Console.Write("Matrices can't be compared:\n");
} else {
    Console.Write("Comparison of Matrices: \n");
    for (i = 0; i < row1; i++) {
        for (j = 0; j < col1; j++) {
            if (arr1[i, j] != arr2[i, j]) {
                flag = 0;
                break;
            }
        }
    }
    if (flag == 1)
        Console.Write("Our matrices are equal!\n\n");
    else
        Console.Write("Our matrices are not equal!");
}

전체 예제 코드

사용자로부터 두 행렬의 크기와 요소를 입력받아 동일 여부를 판별하는 완성된 코드입니다.

using System;

namespace Demo {
    public class ApplicationOne {
        public static void Main() {
            int[] arr1 = new int[10, 10];
            int[] arr2 = new int[10, 10];
            int flag = 1;
            int i, j, row1, col1, row2, col2;

            Console.Write("Rows in the 1st matrix: ");
            row1 = Convert.ToInt32(Console.ReadLine());
            Console.Write("Columns in the 1st matrix: ");
            col1 = Convert.ToInt32(Console.ReadLine());
            Console.Write("Rows in the 2nd matrix: ");
            row2 = Convert.ToInt32(Console.ReadLine());
            Console.Write("Columns in the 2nd matrix: ");
            col2 = Convert.ToInt32(Console.ReadLine());

            Console.Write("Elements in the first matrix:\n");
            for (i = 0; i < row1; i++) {
                for (j = 0; j < col1; j++) {
                    Console.Write("element - [{0}],[{1}] : ", i, j);
                    arr1[i, j] = Convert.ToInt32(Console.ReadLine());
                }
            }

            Console.Write("Elements in the second matrix:\n");
            for (i = 0; i < row2; i++) {
                for (j = 0; j < col2; j++) {
                    Console.Write("element - [{0}],[{1}] : ", i, j);
                    arr2[i, j] = Convert.ToInt32(Console.ReadLine());
                }
            }

            Console.Write("Matrix 1:\n");
            for (i = 0; i < row1; i++) {
                for (j = 0; j < col1; j++)
                    Console.Write("{0} ", arr1[i, j]);
                Console.Write("\n");
            }

            Console.Write("Matrix 2:\n");
            for (i = 0; i < row2; i++) {
                for (j = 0; j < col2; j++)
                    Console.Write("{0} ", arr2[i, j]);
                Console.Write("\n");
            }

            if (row1 != row2 || col1 != col2) {
                Console.Write("Matrices can't be compared:\n");
            } else {
                Console.Write("Comparison of Matrices: \n");
                for (i = 0; i < row1; i++) {
                    for (j = 0; j < col1; j++) {
                        if (arr1[i, j] != arr2[i, j]) {
                            flag = 0;
                            break;
                        }
                    }
                }
                if (flag == 1)
                    Console.Write("Our matrices are equal!\n\n");
                else
                    Console.Write("Our matrices are not equal!");
            }
        }
    }
}

실행 결과

2×2 크기의 두 행렬에 같은 값을 입력했을 때의 실행 결과입니다.

Rows in the 1st matrix: 2
Columns in the 1st matrix: 2
Rows in the 2nd matrix: 2
Columns in the 2nd matrix: 2
Elements in the first matrix:
element - [0],[0] : 1
element - [0],[1] : 2
element - [1],[0] : 3
element - [1],[1] : 4
Elements in the second matrix:
element - [0],[0] : 1
element - [0],[1] : 2
element - [1],[0] : 3
element - [1],[1] : 4
Matrix 1:
1 2
3 4
Matrix 2:
1 2
3 4
Comparison of Matrices:
Our matrices are equal!

정리

두 행렬의 동일 여부는 ① 크기(차원)가 같은지 먼저 확인하고, ② 모든 요소를 순회하며 하나라도 다른 값이 있는지 검사하는 방식으로 판별할 수 있습니다. 플래그 변수를 활용하면 다른 요소를 발견한 즉시 비교를 중단할 수 있어 불필요한 연산을 줄일 수 있다는 장점도 있습니다.