VesselWheel

수박수? 반복패턴 만들기 본문

Coding Test Practice in Swift

수박수? 반복패턴 만들기

JasonYang 2023. 11. 27. 09:56

문제

 

풀이

func solution(_ n:Int) -> String {
    // 0부터 n-1까지 범위 생산
    // map 함수를 이용하여 짝수, 홀수 구분 // map 명령 배열 내에 조건에 따라 실행해라.
    // reduce 함수 배열의 모든 요소 결합, 초기값으로 "" String 빈문자열, 다음 자리부터 더하기
    return (0 ..< n).map{($0 % 2 == 0 ? "수":"박")}.reduce("", +)
}

 

Tip

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]

'Coding Test Practice in Swift' 카테고리의 다른 글

내적 구하기 ft. 스칼라  (0) 2023.11.28
제곱근 구하기  (0) 2023.11.27
제일 작은 수 제거하기  (1) 2023.11.23
없는 숫자 더하기  (2) 2023.11.23
핸드폰 번호 가리기  (0) 2023.11.23