-
Swift 백준 1000번: A+B알고리즘/Swift 2021. 6. 29. 00:59
문제
두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.
입력
첫째 줄에 A와 B가 주어진다. (0 < A, B < 10)
출력
첫째 줄에 A+B를 출력한다.
Solution
가장 기본적인 문제 A+B를 Swift로 풀면서 막힌 건 입력이었다..!
앱을 만들면서 Swift로는 입력을 받을 일은 없으니 당연히 해본 적이 없었다. 그 외에도 필요한 함수들부터 알아보자!
func readLine(strippingNewline: Bool = true) -> String?
Function :: Returns a string read from standard input through the end of the current line or until EOF(end-of-file) is reached.
입력을 받기 위해서는 시작 글에서 말했듯이 엑스코드에서 프로젝트를 만들어주고 해야 한다.
표준 입력에서 읽은 문자열을 반환해준다.
func components(separatedBy separator: String) -> [String]
Instance Method :: Returns an array containing substrings from the receiver that have been divided by a given separator.
주어진 구분 기호로 나눈 부분 문자열들을 포함한 배열을 반환
func split(separator: Character, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true) -> [Substring]
Instance Method :: Returns the longest possible subsequences of the collection, in order, around elements equal to the given element.
주어진 요소와 동일한 요소 주위의 컬렉션에서 가장 긴 하위 시퀀스를 순서대로 반환
func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]
Generic Instance Method :: Returns an array containing the results of mapping the given closure over the sequence’s elements.
시퀀스의 요소들과 주어진 클로져를 맵핑한 결과가 포함된 배열을 반환
func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result
Generic Instance Method :: Returns the result of combining the elements of the sequence using the given closure.
주어진 클로져를 사용해 시퀀스의 요소들을 합친 결과를 반환
첫 번째 풀이 코드
import Foundation let line = readLine() if let line = line { let array = line.components(separatedBy: " ") print(Int(array[0])! + Int(array[1])!) }
12ms
간단하게 입력받고 공백을 기준으로 나누어 배열 값을 가져와 더했다.
components function은 foundation 라이브러리를 import 해줘야 한다. 메모리랑 시간이 꽤 차지하기에 필요 없으면 쓰지 않는게 좋다고 한다.
두 번째 풀이 코드
print((readLine()?.split(separator: " ").map { Int($0)! }.reduce(0, +))!)
import Foundation을 안 쓰고 한 줄로 끝내고 8ms 걸리는 코드를 보았다..!
map, reduce를 잘 활용하면 가능한 거 같다.(문법을 자세히 공부해놔야겠다.)
참고 사이트
https://jusung.gitbook.io/the-swift-language-guide/language-guide/02-basic-operators
기본 연산자 (Basic Operators)
jusung.gitbook.io
https://developer.apple.com/documentation/swift/swift_standard_library
Apple Developer Documentation
developer.apple.com
'알고리즘 > Swift' 카테고리의 다른 글
Swift 알고리즘 : DFS & BFS (0) 2022.03.26 Swift 백준 1436번: 뒤집기 (0) 2022.01.17 Swift Algorithm 시작 (0) 2021.06.29