ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [알고리즘 문제] 프로그래머스 행렬의 곱셈
    IT/알고리즘 2019. 5. 22. 11:00




    중학교때 많이 풀었던 행렬의 곱셈을 자바코드로 작성해보자.


    너무 오래되서 계산방법이 헷갈렷...........


    첫번째 행렬의 열의 수와 두번째 행렬의 행의 수가 같아야 곱셈이 가능하다.

    곱셈으로 인해 생성되는 행렬은 첫번째 행렬의 행, 두번째 행렬의 열의 크기만하다.


    예)


    [2][3]        [3][2]        [2][2]


    1 2 3        1 2            6 12

    1 2 3    x   1 2     =     6 12

    1 2



    이 점을 꼭 생각하면서 풀어야한다!!!


    소스코드 ↓↓↓


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    public class matrix {
        public static void main(String[] args) {
            
            Scanner scan = new Scanner(System.in);
            
            System.out.println("첫번째 행렬 크기 입력");
            int x = scan.nextInt();
            int y = scan.nextInt();
            
            System.out.println("두번째 행렬 크기 입력");
            int x2 = scan.nextInt();
            int y2 = scan.nextInt();
            
            int[][] arr = new int[x][y];
            int[][] arr2 = new int[x2][y2];
            
            int[][] arr3 = new int[x][y2];
            
            
            System.out.println("첫번째 행렬 값 입력");
            for(int i=0; i<x; i++){
                for(int j=0; j<y; j++){
                    arr[i][j] = scan.nextInt();
                }
            }
            
            System.out.println("두번째 행렬 값 입력");
            for(int i=0; i<x2; i++){
                for(int j=0; j<y2; j++){
                    arr2[i][j] = scan.nextInt();
                }
            }
            
            //행렬곱셈
            for(int i=0; i<x; i++){
                for(int j=0; j<y2; j++){
                    int sum = 0;
                    for(int k=0; k<y; k++){
                        sum+=arr[i][k]*arr2[k][j];
                    }
                    arr3[i][j] = sum;
                }            
            }
            
            
            //출력
            for(int i=0; i<x; i++){
                for(int j=0; j<y2; j++){
                    System.out.print(arr3[i][j] + " ");
                }
                System.out.println();
            }
            
        }
    }
    cs




    실행결과 ↓↓↓






    수학은 넘 어려웡



    댓글

Designed by Tistory.