행렬의 곱셈 Level 2
행렬의 곱셈을 유심히 분석해 본 결과 for문을 세번이나 사용해야 가능한다는 것을 알 수 있었다.
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];
}
}
}
A,B행렬의 각 요소를 곱한 다음 K위치 만큼 움직이며 계속 더해 나가면 행렬의 곱셈이 된다.
2차원 행렬이면 그 크기에 상관없이 모두 적용가능하다.
# Arrays.deepToString : 2차원(혹은 그 이상) 배열을 String으로 표현해준다.
# Arrays.toString : 1차원 배열을 String으로 표현해준다.
import java.util.Arrays; class ProductMatrix { public int[][] productMatrix(int[][] A, int[][] B) { int[][] answer = new int[A.length][B[0].length]; if (A[0].length == B.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]; //A는 열이, B는 행이 자유롭게 움직임 -> k // answer[0][0] += A[0][0]*B[0][0] + A[0][1]*B[1][0]; // answer[0][1] += A[0][0]*B[0][1] + A[0][1]*B[1][1]; // answer[1][0] += A[1][0]*B[0][0] + A[1][1]*B[1][0]; // answer[1][1] += A[1][0]*B[0][1] + A[1][1]*B[1][1]; } System.out.print("answer[" + i + "][" + j+ "] : "); System.out.println(answer[i][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("행렬의 곱셈 : " + Arrays.deepToString(c.productMatrix(a, b))); } }
'프로그래밍 > 알고리즘(자바)' 카테고리의 다른 글
야근 지수 Level 3 #Collection.reverse (0) | 2018.05.08 |
---|---|
하샤드수 Level 2 #return 조건문 #foreach문 (0) | 2018.05.07 |
정수 내림차순으로 배치하기 Level 2 #split #Arrays.sort #Collections.reverse #Arrays.asList #String.join (0) | 2018.05.07 |
2016년 Level 2 #달력(요일) 알고리즘 (0) | 2018.05.07 |
콜라츠 추측 Level 2 #삼항연산자 (0) | 2018.05.07 |