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.zig
const std = @import("std");

fn show(value: i64) !void {
    var buffer: [64]u8 = undefined;
    var writer = std.fs.File.stdout().writer(&buffer);
    try writer.interface.print("{d}\n", .{value});
    try writer.interface.flush();
}

pub fn main() !void {
    const items = [_]i64{2, 2, 5};
    var seen = [_]i64{0, 0, 0, 0, 0, 0};
    var distinct: i64 = 0;
    var i: i64 = 0;
    while (i < 3) {
        const value: i64 = items[@intCast(i)];
        if (seen[@intCast(value)] == 0) {
            seen[@intCast(value)] = 1;
            distinct += 1;
        }
        i += 1;
    }
    try show(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.