VesselWheel

없는 숫자 더하기 본문

Coding Test Practice in Swift

없는 숫자 더하기

JasonYang 2023. 11. 23. 18:42

문제 

 

풀이

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(_:_:) 

Returns the result of combining the elements of the sequence using the given closure.
func reduce<Result>(
    _ initialResult: Result,
    _ nextPartialResult: (Result, Self.Element) throws -> Result
) rethrows -> Result
더보기

Parameters 

initialResult

The value to use as the initial accumulating value. initialResult is passed to nextPartialResult the first time the closure is executed.

nextPartialResult

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:

  1. The nextPartialResult closure is called with initialResult—0 in this case—and the first element of numbers, returning the sum: 1.
  2. The closure is called again repeatedly with the previous call’s return value and each element of the sequence.
  3. 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