[Algorithm] Swift로 알고리즘 문제를 풀기 위해 필요한 Basic 문법
jane1choi opened this issue · comments
키보드 입력
키보드 입력 받기
let value = readLine()
readLine()
의 리턴값은 Optional String이니 필요한 데이터에 따라 알아서 가공해야 한다.
키보드 입력받은 값 공백으로 구분하기
- split()
let nums = readLine()!.split(seperator:" ") // ["1", "2", "3", "4"]
- component()
let nums = readLine()!.components(seperatedBy:" ") // ["1", "2", "3", "4"]
둘의 차이점은?
-
import Foundation
split()의 경우 Swift 기본 instance method여서 Foundation 없이도 사용 가능하지만
component() 의 경우 Foundation에 들어있는 instance method이기 때문에
반드시 import Foundation을 해줘야 한다!! (그러면 용량이 늘어나게 됨..)
그렇다면 component()를 사용하는 이유는? -
리턴 타입이 다르다
split()으로 쪼갠 nums는 리턴 타입이 [String.SubSequence]이고,
components()로 쪼갠 nums2는 리턴 타입이 [String]이다. 따라서, components()로 쪼갠 값은 바로 String으로 쓸 수 있지만, split()으로 쪼갠 값은 바로 String으로 쓸 수 없다는 것..! (물론 뒤에서 소개할 map을 이용해 간단하게 변환 가능하다!)배열(Array) 다루기
알고리즘 문제 풀 때 배열을 다룰 일이 굉장히 많다! 잘 알아두자 !
- 빈 배열 만들기
var empty : [Int] = []
var empty = [Int]()
var empty : Array<Int> = []
- 임의의 data 넣어서 만들기
var array = Array(1...4) // [1,2,3,4]
- 크기가 정해진 배열
var arr = Array(repeating: 0, count: 3) // [0,0,0]
- 2차원 배열(Matrix) 만들기
let matrix = [[Int]]()
let arr: [[Int]] = Array(repeating:Array(repeating:1, count: 5), count: 3) // 안쪽 count가 행, 바깥 count가 열
// 다룰때는 이렇게
arr[i][j]
- 배열 거꾸로 출력
array.reversed()
- 배열 정렬하기
array.sorted() // default는 오름차순 (1,2,3...)
array.sorted(by: >) // 내림차순으로 정렬
배열을 다룰 때 가장 중요한 세 가지 map
, filter
, reduce
- map
var string = ["1","2","3","4"]
string.map { Int($0)! } // [1,2,3,4] 각 원소를 전부 Int로 맵핑
- filter
var array = [1,2,3,4]
array.filter { $0 % 2 == 0 } // [2,4] 조건에 맞는 수만 뽑아냄
- reduce
var array = [1,2,3,4]
array.reduce(0, +) // 숫자 합이 나타남. 문자열 합치기도 가능
String, SubString, Index 다루기
// n번째 문자 index 구하는 법
let index = string.index(string.startIndex, offsetBy: n-1)
// subString 구하는 법
let substring = string[start...end]
// 문자 검색해서 index 찾기
"abc123".index(firstOf: "c")
// 특정 character replace
string.replacingOccurences(of:" ", with:"+")
print할 때 따옴표(')나 쌍따옴표(") 출력하기
print("안녕 \" 하세요") \\ 결과: 안녕 " 하세요
비트 연산
- NOT : ~value // 00001111 -> 11110000 으로. 0과 1을 바꿔준다
- AND : first & second // 두 개 자릿수가 둘 다 1일 때 1 리턴
- OR : first | second // 둘 중 하나라도 자릿수가 1이면 1 리턴
- XOR : first ^ second // 두 자릿수가 다르면 1, 같으면 0 리턴
- Left Shift : value << n // n만큼 왼쪽으로 이동하고 빈자리는 0으로 채운다
- Right Shift : value >> n // n만큼 오른쪽으로 이동하고 빈자리는 0으로
- 3항 연산자 : 조건문 ? 참 : 거짓 // a < b ? a: b 중첩도 가능
앱 종료
exit(0)
무한 루프
while true {
...
}
do while문
repeat {
....
} while
절대값 변환
abs(-29) // 29
for문에서 원하는 수치만큼 증가 or 감소하는 반복문 필요할 때
Swift에는 증감연산자(++, --)가 없다..!
for i in stride(from: 1, to: 5, by: 2) {
print(i)
}
// 1
// 3
for i in stride(from: 1, through: 5, by: 2) {
print(i)
}
// 1
// 3
// 5
Dictionary 사용하기
- 생성
var dic: [Int : String] = [ : ]
var dic = [Int : String]()
var dic = [1 : "a", 2 : "b", 3 : "c"]
- 값 수정
dic.updateValue("c", forKey: 3)
dic[3] = "d"
- 값 추가
dic[4] = "5"
dic.update("5", forKey: 4) // 4라는 키가 있을 경우 수정이 됨
- 접근
dic[4]! // Unwrapping을 해준다
- for문 돌기
for (key, value) in dic {
print(key) // 1,2,3
print(value) // a,b,c
}
단, 순서대로 찍히지 않는다! (Dictionary는 순서가 없음)
- 값 삭제
dic.removeValue(forKey:4) // 특정 키값 삭제
dic.removeAll() // 전체 삭제
-
Key를 바꿀 경우, 지우고 다시 넣어줘야 함
-
Dictionary Key로 sort하기
let sort = dic.sorted(by: { $0.key < $1.key }) // value로 sort할 경우
$0.value
[참고 자료] https://twih1203.medium.com/swift-알고리즘에-필요한-swift-basic-총정리-d86453bbeaa5