차집합과 대칭 차집합
Coddy Swift 여정의 로직 및 흐름 섹션에 포함된 레슨 — 56개 중 20번째.
두 가지 집합 연산이 더 추가되어 툴킷을 완성합니다.
subtracting은 첫 번째 집합의 요소 중 두 번째 집합에 포함되지 않은 요소를 반환합니다:
let a: Set = [1, 2, 3, 4]
let b: Set = [3, 4, 5]
a.subtracting(b) // {1, 2}symmetricDifference는 두 집합 중 정확히 한 곳에만 포함되어 있고, 두 곳 모두에는 포함되지 않은 요소들을 반환합니다:
a.symmetricDifference(b) // {1, 2, 5}union 및 intersection과 함께, 이 네 가지는 여러분이 일상에서 접하게 될 모든 집합 대수 문제를 다룹니다.
집합 포함 여부 확인은 필터로서도 유용합니다. 어떤 값이 집합에 속해 있는지 O(1)으로 확인해 보세요:
let stopwords: Set = ["the", "a", "an"]
let words = ["the", "cat", "sat", "on", "a", "mat"]
let real = words.filter { !stopwords.contains($0) }
// ["cat", "sat", "on", "mat"]챌린지
쉬움두 줄의 입력을 읽으십시오. 각 줄은 쉼표로 구분된 문자열 목록입니다. 각각을 currentMembers와 renewedMembers로 취급하십시오.
세 줄을 출력하십시오. 각 줄은 알파벳순으로 정렬되고 ,로 연결되어야 합니다 (해당 항목이 없는 경우 비워둡니다):
Lapsed: <...>> current에서 renewed를 뺀 차집합New: <...>> renewed에서 current를 뺀 차집합Stayed: <...>> 두 집합의 교집합
첫 번째 줄에 alice,bob,cara가 입력되고 두 번째 줄에 bob,cara,dan이 입력될 경우, 출력은 다음과 같습니다:
Lapsed: alice
New: dan
Stayed: bob,cara치트 시트
subtracting은 첫 번째 집합에는 있지만 두 번째 집합에는 없는 요소들을 반환합니다:
let a: Set = [1, 2, 3, 4]
let b: Set = [3, 4, 5]
a.subtracting(b) // {1, 2}symmetricDifference는 두 집합 중 정확히 어느 한 쪽에만 있는 요소들을 반환합니다:
a.symmetricDifference(b) // {1, 2, 5}contains를 사용하여 세트를 O(1) 필터로 사용하세요:
let stopwords: Set = ["the", "a", "an"]
let words = ["the", "cat", "sat", "on", "a", "mat"]
let real = words.filter { !stopwords.contains($0) }
// ["cat", "sat", "on", "mat"]직접 해보기
let current = Set(readLine()!.components(separatedBy: ","))
let renewed = Set(readLine()!.components(separatedBy: ","))
// TODO: Lapsed (current - renewed), New (renewed - current), Stayed (intersection)를 출력하세요
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.