swift

swift - set #2 (Comparing Sets, Combining Sets)

행복하게사는게꿈 2021. 1. 7. 04:57

set #2

Comparing Sets

var a: Set = [1, 2, 3, 4, 5, 6, 7, 8, 9]
var b: Set = [1, 3, 5, 7, 9]
var c: Set = [2, 4, 6, 8, 10]
let d: Set = [1, 7, 5, 9, 3]


a == b
a != b

// set은 순서가 없기 때문에 요소의 동일성만 판단
b == d

// 두 컬렉션에 저장된 요소를 순서대로 비교하는 메서드기 때문에 실행할 떄 마다 달라짐
b.elementsEqual(d)

// 올바른 결과를 얻고 싶다면 Set을 배열로 바꾼후 정렬하고 비교해야 함 -> 비교할때는 보통 배열이 더 낫다.


// Set은 집합확인이 좋다
// 부분집합 확인
a.isSubset(of: a)
// 진부분집합 확인
a.isStrictSubset(of: a)

// 부분집합 확인
b.isSubset(of: a)
// 진부분집합 확인
b.isStrictSubset(of: a)


// 상위집합 확인
a.isSuperset(of: a)
a.isStrictSubset(of: a)

a.isSuperset(of: b)
a.isStrictSuperset(of: b)

a.isSuperset(of: c)
a.isStrictSuperset(of: c)

// 교집합 확인
// 교집합이면 false , 서로소 집합이면 true
a.isDisjoint(with: b)
a.isDisjoint(with: c)
b.isDisjoint(with: c)

Combining Sets

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [1, 3, 5, 7, 9]
c = [2, 4, 6, 8, 10]

// 합집합 구하기
var result = b.union(c)
result = b.union(a)

// 원본을 직접 변경하는 메소드
// form으로 시작하는 메소드는 원본을 직접 변경한다
b.formUnion(c)
b

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [1, 3, 5, 7, 9]
c = [2, 4, 6, 8, 10]

// 교집합 구하기
// 새로운 메소드로 만들어줌
result = a.intersection(b)

// 교집합 없으면 빈 Set 리턴됨
result = c.intersection(b)

a.formIntersection(b)
a

b.formIntersection(c)
b



a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [1, 3, 5, 7, 9]
c = [2, 4, 6, 8, 10]

// 여집합 구하기
result = a.symmetricDifference(b)
result = c.symmetricDifference(b)

a.formSymmetricDifference(b)

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [1, 3, 5, 7, 9]
c = [2, 4, 6, 8, 10]

// 차집합 구하기
result = a.subtracting(b)

// 원본 변경하고 싶다면
a.subtracting(b)