Lesson contents

Sets and set operations

A set keeps each distinct value once. Use membership, union, intersection or difference when the question is about who belongs.

Simple example

Add 2, 2 and 5 to a set. Print how many different values it contains.

Start2 2 5
Result2
Lesson.scala
object Lesson {
  def main(args: Array[String]): Unit = {
        var items = Array(2, 2, 5)
        var seen = Array(0, 0, 0, 0, 0, 0)
        var distinct = 0
        var i = 0
        while (i < 3) {
            var value = items(i)
            if (seen(value) == 0) {
                seen(value) = 1
                distinct += 1
            }
            i += 1
        }
        println(distinct)
  }
}
Output
2
Advertisements

Everyday examples

Count unique visitors

Badges 8, 3, 8 and 4 are scanned. How many different people attended?

Start8 3 8 4
Result3

The second scan of 8 adds no new member. The distinct badges are 8, 3 and 4.

Find students in both clubs

Music has students 2 and 4. Drama has 4 and 7. Who is in both?

Start2,4 4,7
Result4

Intersect the two sets. Student 4 is the only member present in both.

Find outstanding forms

Forms are due from 1, 2 and 3. Students 1 and 3 have submitted. Who still owes a form?

Start1,2,3 1,3
Result2

Subtract the submitted set from the expected set. Only student 2 remains.

Cost and limits

A set discards repeated occurrences. Keep counts in a map if you need to know how often a value appeared.