본문 바로가기
백준 알고리즘/Swift

Swift - 백준 #10871 X보다 작은 수

by minsol Kim 2023. 11. 28.

https://www.acmicpc.net/problem/10871

 

10871번: X보다 작은 수

첫째 줄에 N과 X가 주어진다. (1 ≤ N, X ≤ 10,000) 둘째 줄에 수열 A를 이루는 정수 N개가 주어진다. 주어지는 정수는 모두 1보다 크거나 같고, 10,000보다 작거나 같은 정수이다.

www.acmicpc.net

import Foundation

let input = readLine()!.split(separator: " ").map{Int($0)!}
let x = input[1]
let a = readLine()!.split(separator: " ").map{Int($0)!}.filter{$0 < x}
//terminator 사용하여 공백
a.forEach {
    print($0, terminator: " ")
}

 

filter 고차함수를 사용해봤다. 

일단 고차함수란 다른 함수를 전달인자로 받거나 함수 실행의 결과를 함수로 반환하는 함수를 뜻한다.

filter 은 기존 컨테이너에서 내부의 값을 걸러 새로운 컨테이너를 만든다. 

그리고 forEach는 반복실행하려는 코드를 파라미터로 받고, 저장된 요소는 클로저 상수로 전달된다. 

즉,

print($0, terminator: " ") 를 찍는 클로저를 a의 개수만큼 반복하는 것이다. 

terminator는 문자열의 끝에 개행 대신 들어갈 문자를 나타낸다. 

 

참고한 글 

 

https://developer.apple.com/documentation/swift/print(_:separator:terminator:)

 

print(_:separator:terminator:) | Apple Developer Documentation

Writes the textual representations of the given items into the standard output.

developer.apple.com

https://babbab2.tistory.com/81

 

Swift) 클로저(Closure) 정복하기(1/3) - 클로저, 누구냐 넌

안녕하세요 :) 소들입니다 으휴 저번 주도 쓸데없이 바빴어서 포스팅을 못했네용 나태한 저번주의 나를 반성하며.. 하암..🥱 음 전에 제가 Swift의 꽃이 Optional이라고 말한 적 있는데, Optional 만큼

babbab2.tistory.com

 

'백준 알고리즘 > Swift' 카테고리의 다른 글

Swift - 백준 #10807 개수세기  (1) 2023.11.27
Swift- 백준 #11022 A + B - 8  (0) 2023.11.26
Swift - 백준 #25304 영수증  (1) 2023.11.25
Swift - 백준 #1330 두 수 비교하기  (0) 2023.11.23

댓글