포스트

192. 내적


1
2
3
4
5
6
7
8
9
10
11
12
13
14
import Foundation

func solution(_ a:[Int], _ b:[Int]) -> Int {

    var answer : Int = 0

    for i in a.indices{
        answer += a[i]*b[i]
    }

    return answer
}



for문을 사용해서 해결했는데 다른코드들을 보니 zip이 있었다.

다른코드

1
2
3
4
5
import Foundation

func solution(_ a:[Int], _ b:[Int]) -> Int {
    return zip(a, b).map(*).reduce(0, +)
}

zip

  • 2개 이상의 시퀀스를 조합하여 하나의 새로운 시퀀스를 생성한다.
  • zip함수를 사용하면 여러 시퀀스들을 병렬로 순회하며 요소들을 조합 할 수 있다.
  • zip은 각 시퀀스에서 동일한 인덱스의 요소들을 묶어 새로운 튜플 시퀀스로 반환한다.
1
2
3
4
5
6
7
8
9
zip(sequence1, sequence2, sequence3, ...)
let numbers = [1, 2, 3, 4, 5]
let strings = ["One", "Two", "Three", "Four", "Five"]

let zipped = zip(numbers, strings)

for (number, string) in zipped {
    print("\(number) is \(string)")
}
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.