VesselWheel

내적 구하기 ft. 스칼라 본문

Coding Test Practice in Swift

내적 구하기 ft. 스칼라

JasonYang 2023. 11. 28. 10:00

 

들어가기 앞서, 

내적(스칼라곱) 이란

https://ko.wikipedia.org/wiki/%EC%8A%A4%EC%B9%BC%EB%9D%BC%EA%B3%B1

두 벡터의 좌표가 각각의 배열 a = [a1, a2, ...], b = [b1, b2]을 가지고 있을 때, 이 둘의 스칼라곱은 같은 위치의 성분을 곱한 뒤. 모두 합하여 얻는 값이다. 

 

 

 

문제

 

풀이

func solution(_ a: [Int], _ b: [Int]) -> Int {
    // 조건문으로 두 벡터의 길이가 같지 않으면 guard 조건문을 실행 
    guard a.count == b.count else {
        // 두 배열의 길이가 다르면 예외 처리 또는 기본값 반환
        return 0
    }

    var result = 0
    for i in 0..<a.count {
        result += a[i] * b[i]
    }
    return result
}

 

다른 풀이

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

 

Tip

 

Zip()

zip(_:_:)

Creates a sequence of pairs built out of two underlying sequences.
iOS 8.0+ macOS 10.10+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+ visionOS 1.0+ Beta
func zip<Sequence1, Sequence2>(
    _ sequence1: Sequence1,
    _ sequence2: Sequence2
) -> Zip2Sequence<Sequence1, Sequence2> where Sequence1 : Sequence, Sequence2 : Sequence

Parameters 

sequence1

The first sequence or collection to zip.

sequence2

The second sequence or collection to zip.

Return Value

A sequence of tuple pairs, where the elements of each pair are corresponding elements of sequence1 and sequence2.

 

Discussion

In the Zip2Sequence instance returned by this function, the elements of the ith pair are the ith elements of each underlying sequence. The following example uses the zip(_:_:)function to iterate over an array of strings and a countable range at the same time:

let words = ["one", "two", "three", "four"]
let numbers = 1...4


for (word, number) in zip(words, numbers) {
    print("\(word): \(number)")
}
// Prints "one: 1"
// Prints "two: 2"
// Prints "three: 3"
// Prints "four: 4"

If the two sequences passed to zip(_:_:) are different lengths, the resulting sequence is the same length as the shorter sequence. In this example, the resulting array is the same length as words:

let naturalNumbers = 1...Int.max
let zipped = Array(zip(words, naturalNumbers))
// zipped == [("one", 1), ("two", 2), ("three", 3), ("four", 4)]

 

 

Map()함수

Instance Method

map(_:)

Returns an array containing the results of mapping the given closure over the sequence’s elements.
iOS 8.0+ macOS 10.10+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+ visionOS 1.0+ Beta
func map<T>(_ transform: (Self.Element) throws -> T) rethrows -> [T]

Parameters 

transform

A mapping closure. transform accepts an element of this sequence as its parameter and returns a transformed value of the same or of a different type.

Return Value

An array containing the transformed elements of this sequence.

Discussion

In this example, map is used first to convert the names in the array to lowercase strings and then to count their characters.

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let lowercaseNames = cast.map { $0.lowercased() }
// 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
let letterCounts = cast.map { $0.count }
// 'letterCounts' == [6, 6, 3, 4]