Union and Intersection
Part of the Logic & Flow section of Coddy's Swift journey — lesson 19 of 56.
Sets shine when you ask membership questions involving two collections.
let a: Set = [1, 2, 3, 4]
let b: Set = [3, 4, 5, 6]union returns every element from either side:
a.union(b) // {1, 2, 3, 4, 5, 6}intersection returns only the elements that appear in both:
a.intersection(b) // {3, 4}Each method returns a new Set. The original sets stay untouched. Iteration order over the result is not guaranteed, sort before printing.
Challenge
EasyRead two lines of input. Each is a comma-separated list of integers.
Treat them as sets a and b. Print two lines:
- The intersection, sorted ascending, joined with
,(or an empty line when empty) - The union, sorted ascending, joined with
,
For input 1,2,3,4 on the first line and 3,4,5,6 on the second, the output is:
3,4
1,2,3,4,5,6Cheat sheet
Set operations in Swift:
let a: Set = [1, 2, 3, 4]
let b: Set = [3, 4, 5, 6]
a.union(b) // {1, 2, 3, 4, 5, 6} - elements from either set
a.intersection(b) // {3, 4} - elements in both setsBoth methods return a new Set; originals are unchanged. Sort before printing since iteration order is not guaranteed.
Try it yourself
let a = Set(readLine()!.components(separatedBy: ",").map { Int($0)! })
let b = Set(readLine()!.components(separatedBy: ",").map { Int($0)! })
// TODO: intersection sorted joined, union sorted joined
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Count and IndicesCase and TrimSearching in StringsSplitting and JoiningReplacing SubstringsRecap - Username Check4Sets
Creating SetsUnion and IntersectionSubtracting and SymmetricSubset and SupersetRecap - Tag Filter