프로그래밍

프로그래머스 C# 행렬의 곱셈(3중 for문, JAVA)

노마드선샤인 2023. 2. 11. 14:50
728x90

using System;

public class Solution {
    public int[,] solution(int[,] arr1, int[,] arr2) {
        int[,] answer = new int[arr1.GetLength(0),arr2.GetLength(1)];
        
        for(int i = 0;i<arr1.GetLength(0);i++)
        {
            for(int j = 0;j<arr2.GetLength(0);j++)
            {
                for (int k = 0; k < arr2.GetLength(1); k++)
                {
                    answer[i, k] += arr1[i, j] * arr2[j, k];
                }
            }
        }
        
        return answer;
    }
}

 

 

자바

 

class ProductMatrix {
    public int[][] productMatrix(int[][] A, int[][] B) {
        int[][] answer = new int[A.length][B[0].length];
        for(int i=0;i<answer.length;i++)
        {
            for(int j=0;j<answer[0].length;j++)
            {
                for(int k=0;k<A[0].length;k++)
                {
                    answer[i][j]+=A[i][k]*B[k][j];
                }
            }
        }
    return answer;
    }

    public static void main(String[] args) {
        ProductMatrix c = new ProductMatrix();
        int[][] a = { { 1, 2 }, { 2, 3 } };
        int[][] b = { { 3, 4 }, { 5, 6 } };
      // 아래는 테스트로 출력해 보기 위한 코드입니다.
      System.out.println("행렬의 곱셈 : " + c.productMatrix(a, b));
    }
}

 

 

728x90