-
[Swift] 음양 더하기Coding Test 2023. 11. 6. 00:07
import Foundation func solution(_ absolutes:[Int], _ signs:[Bool]) -> Int { var count:Int = 0 var result:Int = 0 for input in signs { if input == true { result += absolutes[count] } else { result -= absolutes[count] } count += 1 } return result }
1) 두 배열을 튜플로 만들기
import Foundation func solution(_ absolutes:[Int], _ signs:[Bool]) -> Int { zip(absolutes, signs) //signs의 값에 따라 수(abslutes)가 변한다 -> 배열로 들어감 .map { $1 ? $0 : -$0 } //줄여서 더한다 .reduce(0, +) }
Functionzip(_:_:)
Creates a sequence of pairs built out of two underlying sequences.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(_:)
Returns an array containing the results of mapping the given closure over the sequence’s elements.let cast = ["Vivien", "Marlon", "Kim", "Karl"] let lowercaseNames = cast.map { $0.lowercased() } // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
'Coding Test' 카테고리의 다른 글
[Swift] 크기가 작은 부분 문자열 (0) 2023.11.15 [Swift] 소수 판별 (1) 2023.11.14 [Swift] 내적 (0) 2023.11.12 [Swift] 추억 점수 (0) 2023.11.02 [Swift] 정수 제곱근 판별 (0) 2023.10.19