
📝 Problem
행렬 덧셈
💡 Solve
import Foundation
func solution(_ x: Int, _ y: Int) -> [[Int]] {
var res = [[Int]]()
let A = maker(x, y)
let B = maker(x, y)
for i in 0 ..< x {
res.append([])
for j in 0 ..< y {
res[i].append(A[i][j] + B[i][j])
}
}
return res
}
func maker(_ x: Int, _ y: Int) -> [[Int]] {
var res = [[Int]]()
for i in 0 ..< x {
res.append([])
res[i].append(contentsOf: readLine()!.split(separator: " ").map { Int($0)! })
}
return res
}
let input = readLine()!.split(separator: " ").map { Int($0)! }
let x = input[0], y = input[1]
let result = solution(x, y)
for i in 0 ..< x {
for j in 0 ..< y {
print(result[i][j], terminator: " ")
}
print()
}
✏️ Explanation
- 메모리 : 79648 KB
- 시간 : 24 ms
- x, y 크기의 배열이 총 2개가 필요하고, 최종 결과도 배열의 형태로 뽑으면 안된다.
- 그래서 maker로 x, y크기의 2차 배열을 각각 만들고 결과를 반환하는 solution을 만들었다.
- 반환된 최종 결과를 예시에 맞게 출력하기 위해 for 문을 또 돌렸다.🙄
- 너무 많은 반복문을 사용한 것 같아서 기분이 좋지 않다.
- 풀고나니까 Array(String)을 이용했어도 괜찮았을 것 같다.
- 오늘의 수확은
res[i].append(contentsOf: readLine()!.split(separator: " ").map { Int($0)! })
!
- contentsOf를 통해 배열에 배열을 더해주는 메서드를 알게됐다!
👀 Reference