기본 콘텐츠로 건너뛰기

프로그래머스 - 행렬의 곱셈

머리속에서는 쉽지만 막상 구현하면 헷갈려서 잘 틀리는 행렬곱...
class ProductMatrix {
    public int[][] productMatrix(int[][] A, int[][] B) {
        if(A[0].length!=B.length)
            return null;
        int[][] answer = new int[A.length][B[0].length];
        for(int i=0;i<A.length;i++) {
            for(int j=0;j<B[0].length;j++) {
                for(int k=0;k<B.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));
    }
}

댓글

이 블로그의 인기 게시물

프로그래머스 - 시저 암호

public class Caesar { String caesar ( String s , int n ) { n %= 26 ; String result = "" ; char [] temp = s . toCharArray (); for ( int i = 0 ; i < temp . length ; i ++) { if ( temp [ i ]>= 'a' && temp [ i ]<= 'z' ) temp [ i ] = ( char ) (( temp [ i ]+ n )> 'z' ? ( temp [ i ]+ n - 1 )% 'z' + 'a' : ( temp [ i ]+ n )); else if ( temp [ i ]>= 'A' && temp [ i ]<= 'Z' ) temp [ i ] = ( char ) (( temp [ i ]+ n )> 'Z' ? ( temp [ i ]+ n - 1 )% 'Z' + 'A' : ( temp [ i ]+ n )); result += temp [ i ]; } return result ; } public static void main ( String [] args ) { Caesar c = new Caesar (); System . out . println ( "s는 'a B z', n은 4인 경우: " + c . caesar ( ...