Set 활용

w0308h 2월 18일 PM 02:29 7 0
w0308h Profile Image Level 9
2 #TIL

  • Set의 활용 >> 집합 연산에 활용 시 유용
let setA: Set<Int> = [1,2,3,4,5]
//let setA: Set = [1,2,3,4,5] //요소의 자료형 생략은 가능
let setB: Set<Int> = [3,4,5,6,7]

print(setA.count)
print(setA.isEmpty)
print(setA.contains(1)) 
//요소 포함 여부 확인 -배열과 동일하지만 해싱 알고리즘 사용으로 더 빠르게 동작

//합집합
let union: Set<Int> = setA.union(setB)
print(union) //[7,2,1,4,3,6,5]

//합집합 오름차순 정렬
let sortedUnion: [Int] = union.sorted() //??Set과 배열이 혼용되냐
print(sortedUnion) //[1,2,3,4,5,6,7]

//교집합
let intersection: Set<Int> = setA.intersection(setB)
print(intersection) //[3,5,4]

//차집합
let substracting: Set<Int> = setA.substracting(setB)
print(substracting) //[2,1]
댓글