Last week we looked at Set.union
. This week we look at Set.intersect
. When dealing with sets (which, remember, by definition, cannot contain duplicate elements), sometimes you have two sets, and you want to know what elements they have in common. That is called the intersection of two sets.
Maybe you have some crazy password policy:
- Passwords must be at least 12 characters;
- Each character must be unique; and
- New passwords may have no more than four characters in common.
You can use a set intersection to determine whether an old password and a new password have too many characters in common:
val oldPwd = "aU*E3)vn'2-=" val newPwd1 = "Uv0&*n2'EI~5" val common1 = oldPwd.toSet intersect newPwd1.toSet // common1: scala.collection.immutable.Set[Char] = // Set(E, *, n, U, v, ', 2) // Too many characters in common! val newPwd2 = "Uv0&6;2'ZI~/" val common2 = oldPwd.toSet intersect newPwd2.toSet // common2: scala.collection.immutable.Set[Char] = // Set(U, v, ', 2) // Just right!