일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
- 러닝타이머
- Protocol
- MKMapItem
- dispatchsource
- Xcode
- CoreLocation
- UICollectionViewFlowLayout
- 영문 개인정보처리방침
- 서체관리자
- AnyObject
- 클로저의 캡슐화
- addannotation
- WeatherManager
- 단일 책임원칙
- swift
- App Store Connect
- Required Reason API
- RunningTimer
- weak var
- Timer
- UIAlertAction
- MKMapViewDelegate
- SwiftUI Boolean 값
- CLLocationManagerDelegate
- 한국어 개인정보처리방침
- Startign Assignments
- weatherKit
- xcode로 날씨앱 만들기
- 러닝기록앱
- font book
- Today
- Total
VesselWheel
없는 숫자 더하기 본문
문제
풀이
import Foundation
func solution(_ numbers:[Int]) -> Int {
let total = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].reduce(0, +)
let sum = numbers.reduce(0, +)
return total - sum
}
해석
1. 배열 [0...9] 를 포함하고 있는 인스턴스 total를 모두 더하기 : reduce(0, +) // 0번째부터 다음 항의 연산자 +로 계산
2. 상수 sum에 매개변수 배열 numbers를 모두 더하기 : reduce(0, +) // 배열안에 모두 더한 상수 sum
3. total 인스턴스에서 sum 인스턴스를 빼면, numbers 배열에 포함되지 않은 수를 모두 더한 값 return
Tip
reduce(_:_:)
func reduce<Result>(
_ initialResult: Result,
_ nextPartialResult: (Result, Self.Element) throws -> Result
) rethrows -> Result
Parameters
initialResultThe value to use as the initial accumulating value. initialResult is passed to nextPartialResult the first time the closure is executed.
A closure that combines an accumulating value and an element of the sequence into a new accumulating value, to be used in the next call of the nextPartialResult closure or returned to the caller.
Return Value
The final accumulated value. If the sequence has no elements, the result is initialResult.
Discussion
Use the reduce(_:_:) method to produce a single value from the elements of an entire sequence. For example, you can use this method on an array of numbers to find their sum or product.
The nextPartialResult closure is called sequentially with an accumulating value initialized to initialResult and each element of the sequence. This example shows how to find the sum of an array of numbers.
let numbers = [1, 2, 3, 4]
let numberSum = numbers.reduce(0, { x, y in
x + y
})
// numberSum == 10
When numbers.reduce(_:_:) is called, the following steps occur:
- The nextPartialResult closure is called with initialResult—0 in this case—and the first element of numbers, returning the sum: 1.
- The closure is called again repeatedly with the previous call’s return value and each element of the sequence.
- When the sequence is exhausted, the last value returned from the closure is returned to the caller.
If the sequence has no elements, nextPartialResult is never executed and initialResult is the result of the call to reduce(_:_:).
'Coding Test Practice in Swift' 카테고리의 다른 글
수박수? 반복패턴 만들기 (2) | 2023.11.27 |
---|---|
제일 작은 수 제거하기 (1) | 2023.11.23 |
핸드폰 번호 가리기 (0) | 2023.11.23 |
음양 더하기 (0) | 2023.11.22 |
나누어 떨어지는 숫자 배열 (0) | 2023.11.22 |