[Java] 행렬 곱셈

프로그래밍/JAVA 2020. 8. 13. 20:27 posted by 야매코더

행렬1, 행렬2  입력하여 곱셈값 반환 

public class test {
    public static int[][] compute(int[][]arr1, int[][]arr2){        
        int[][] answer = new int[arr1.length][arr2[0].length];
        
        for(int i =0 ; i < arr1.length ;  i++) {
            for(int j =0 ; j < arr2[0].length ;  j++) {
                int sum = 0;
                for(int k =0 ; k < arr1[0].length ;  k++) {
                    sum += arr1[i][k] * arr2[k][j];
                }
                answer[i][j] = sum;
            }
        }
        return answer ;
    }

    public static void main(String[] args){
        int[][]arr1 = {{1, 2, 3}, {4, 5, 6},{7, 8, 9}};
        int[][]arr2 = {{2, 3, 4}, {4, 4, 2},{3, 2, 1}};        
       
        int[][]answer = compute(arr1, arr2);
       
        for(int i =0 ; i < arr1.length ;  i++) {
            for(int j =0 ; j < arr2[0].length ;  j++) {
               system.out.print(answer[i][j]);
               system.out.print(", ");
            }
               system.out.print("\n");
        }    
    }

}