Programming Search⌘K

Taskintro

Do set operations

Also called set union, set intersection, set difference, symmetric difference, subset test.

Find the union, intersection, difference and symmetric difference of two sets of words, and test whether one set is a subset of the other.

Task

Make a set of the words of each of two lists, and compare the two sets. The function compare_sets(a, b) returns five values:

  1. the union: the words that are in a or in b;
  2. the intersection: the words that are in a and in b;
  3. the difference: the words that are in a and not in b;
  4. the symmetric difference: the words that are in exactly one of a and b;
  5. true if each word of a is in b, that is, if the set of a is a subset of the set of b.

Each list of words is in ascending order by bytes and has no repeats. For example, compare_sets(["red", "blue", "green"], ["blue", "yellow"]) is (["blue", "green", "red", "yellow"], ["blue"], ["green", "red"], ["green", "red", "yellow"], false).

Each word has 1 or more ASCII letters. A list can be empty and can have a word more than one time.

Solutions

Language Union Intersection Difference Symmetric difference Subset
Python a | b a & b a - b a ^ b a <= b
JavaScript, TypeScript a.union(b) a.intersection(b) a.difference(b) a.symmetricDifference(b) a.isSubsetOf(b)
Java u.addAll(b) i.retainAll(b) d.removeAll(b) union minus intersection b.containsAll(a)
C# u.UnionWith(b) i.IntersectWith(b) d.ExceptWith(b) s.SymmetricExceptWith(b) a.IsSubsetOf(b)
Go a loop a loop a loop a loop the difference is empty
Rust a.union(&b) a.intersection(&b) a.difference(&b) a.symmetric_difference(&b) a.is_subset(&b)
C a merge walk a merge walk a merge walk a merge walk the difference is empty
C++ std::ranges::set_union std::ranges::set_intersection std::ranges::set_difference std::ranges::set_symmetric_difference std::ranges::includes(b, a)
Bash a loop a loop a loop a loop the difference is empty
  • Python. Each operation has an operator and a method, and both make a new set. For example, a ^ b and a.symmetric_difference(b) each "Return a new set with elements in either the set or other but not both."1
  • JavaScript and TypeScript. A Set has a method for each operation. For example, intersection "Takes a set and returns a new set containing elements in both this set and the given set."2 An engine that does not have these methods needs a loop with has, as in the Go solution.
  • Java and C#. The methods change the set that they are called on. For example, C# IntersectWith changes the set "to contain only elements that are present in that object and in the specified collection"3. Thus each solution copies the first set before each operation.
  • Go, C and Bash. These languages have no set operations. The Go and Bash solutions keep each set as the keys of a map and do each operation with a loop that tests membership. The C solution sorts the two arrays and walks them together, as in the merge step of merge sort. In each of them, the set of a is a subset of the set of b when the difference is empty.
  • C++. The set algorithms work on sorted ranges, not on a set type. Thus the solution sorts each vector and removes the repeats first. The algorithms then also work on two std::set objects, which are sorted.
  • Order. A Java TreeSet and a Rust BTreeSet keep their items in order, so these solutions do not sort the results. The other solutions sort each result.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • both-empty: all four lists are empty, and the empty set is a subset of each set, so the subset value is true.
  • empty-a: the empty set of a is a subset of the set of b.
  • empty-b: the difference is all of a, and the set of a is not a subset.
  • equal: two lists with the same words in a different order make the same set. The difference and the symmetric difference are empty, and each set is a subset of the other.
  • disjoint: the sets have no word in common, so the intersection is empty and the symmetric difference is the union.
  • duplicates: a word that is in a list two times is in the set one time.
  • case: a and A are different words. A comes first, because its byte is smaller.

Pitfalls

  • Python an operator needs a set, but a method takes any iterable. "Note, the non-operator versions of union(), intersection(), difference(), symmetric_difference(), issubset(), and issuperset() methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets."1 Also, < tests for a proper subset, which is false for two equal sets. Use <= to test for a subset:
colors = {"red", "blue"}
try:
    colors | ["green"]
except TypeError as e:
    print(type(e).__name__)
print(sorted(colors.union(["green"])))
print(colors < {"red", "blue"}, colors <= {"red", "blue"})
Output
TypeError
['blue', 'green', 'red']
False True
  • JavaScript === compares two sets by identity. Two Set objects with the same items are two objects, so === gives false. To compare the items, compare the sizes and use isSubsetOf, which "Takes a set and returns a boolean indicating if all elements of this set are in the given set."2
const a = new Set(["red", "blue"]);
const b = new Set(["blue", "red"]);
console.log(a === b);
console.log(a.size === b.size && a.isSubsetOf(b));
Output
false
true
  • Java retainAll changes the set. retainAll "Retains only the elements in this set that are contained in the specified collection"4, and addAll and removeAll also change the set. A second variable for the same set does not make a copy. Copy the set first:
import java.util.Set;
import java.util.TreeSet;

public class Main {
  public static void main(String[] args) {
    Set<String> blue = Set.of("blue");
    Set<String> a = new TreeSet<>(Set.of("red", "blue"));
    Set<String> both = a;
    both.retainAll(blue);
    System.out.println(a);
    Set<String> c = new TreeSet<>(Set.of("red", "blue"));
    Set<String> common = new TreeSet<>(c);
    common.retainAll(blue);
    System.out.println(c + " " + common);
  }
}
Output
[blue]
[blue, red] [blue]
  • C# IsProperSubsetOf is false for equal sets. IsSubsetOf and IsProperSubsetOf are different tests. The second one tells if the set is a "proper subset of the specified collection"3, so the other collection must have one or more items that the set does not have. To test if two sets have the same items, use SetEquals:
using System;
using System.Collections.Generic;

var a = new HashSet<string> { "red", "blue" };
var b = new HashSet<string> { "blue", "red" };
Console.WriteLine(a.IsSubsetOf(b) + " " + a.IsProperSubsetOf(b) + " " + a.SetEquals(b));
Output
True False True
  • Go reflect.DeepEqual tells a nil set from an empty set. A nil map and an empty map are both empty sets, but reflect.DeepEqual gives false for them. maps.Equal "reports whether two maps contain the same key/value pairs."5 Use maps.Equal to compare two sets:
package main

import (
	"fmt"
	"maps"
	"reflect"
)

func main() {
	var a map[string]struct{}
	b := map[string]struct{}{}
	fmt.Println(reflect.DeepEqual(a, b), maps.Equal(a, b))
}
Output
false true
  • Rust difference is not symmetric. a.difference(&b) "Visits the values representing the difference, i.e., the values that are in self but not in other."6 Thus b.difference(&a) gives other values. For the values that are in exactly one of the sets, use symmetric_difference. A BTreeSet has the same methods:
use std::collections::BTreeSet;

fn main() {
    let a = BTreeSet::from(["red", "blue"]);
    let b = BTreeSet::from(["blue", "green"]);
    println!("{:?}", a.difference(&b).collect::<Vec<_>>());
    println!("{:?}", b.difference(&a).collect::<Vec<_>>());
    println!("{:?}", a.symmetric_difference(&b).collect::<Vec<_>>());
}
Output
["red"]
["green"]
["green", "red"]
  • C++ std::includes takes the larger range first. std::includes "Checks if the sorted target range [first2, last2) is a subsequence of the sorted source range [first1, last1)."7 Thus includes(x, y) tells if y is in x. To test if small is a subset of big, write includes(big, small):
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> small{"b"};
    std::vector<std::string> big{"a", "b", "c"};
    std::cout << std::boolalpha << std::ranges::includes(small, big) << ' '
              << std::ranges::includes(big, small) << '\n';
}
Output
false true
  • C && is not the intersection of two bit sets. An unsigned value can be a set of small numbers, with one bit for each number. Then a & b is the intersection and a | b is the union. But && is a logical operator: it "has type int and the value 1 if both lhs and rhs compare unequal to zero."8 Thus a && b is 1 for two sets that have no item in common:
#include <stdio.h>

int main(void) {
    unsigned a = 0x3u; /* the set {0, 1} */
    unsigned b = 0x4u; /* the set {2} */
    printf("%d %u %u\n", a && b, a & b, a | b);
    return 0;
}
Output
1 0 7
  • Bash an array without declare -A is not a set of words. An array that is not declared as associative is an indexed array, and for an indexed array, "The subscript is treated as an arithmetic expression that must evaluate to a number greater than or equal to zero."9 In an arithmetic expression, a word such as red is the name of a variable, and an unset variable is 0. Thus each word is the index 0. Use declare -A:
colors=()
colors[red]=1
colors[blue]=1
echo "${#colors[@]}"
declare -A names=()
names[red]=1
names[blue]=1
echo "${#names[@]}"
Output
1
2

Code

The build runs the native tests of each language in a pinned toolchain.

compare_sets.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/do-set-operations/.


def compare_sets(
    a: list[str], b: list[str]
) -> tuple[list[str], list[str], list[str], list[str], bool]:
    """Return the union, intersection, difference and symmetric difference
    of the sets of a and b, each sorted, and whether set(a) is a subset of set(b)."""
    sa, sb = set(a), set(b)
    return (
        sorted(sa | sb),
        sorted(sa & sb),
        sorted(sa - sb),
        sorted(sa ^ sb),
        # <= is subset. < is proper subset, which is false for equal sets.
        sa <= sb,
    )
test_compare_sets.py 24 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/do-set-operations/.

import pytest

from compare_sets import compare_sets

CASES = {
    "colors": (["red", "blue", "green"], ["blue", "yellow"], (["blue", "green", "red", "yellow"], ["blue"], ["green", "red"], ["green", "red", "yellow"], False)),
    "subset": (["b"], ["a", "b", "c"], (["a", "b", "c"], ["b"], [], ["a", "c"], True)),
    "both-empty": ([], [], ([], [], [], [], True)),
    "empty-a": ([], ["x"], (["x"], [], [], ["x"], True)),
    "empty-b": (["x"], [], (["x"], [], ["x"], ["x"], False)),
    "equal": (["a", "b"], ["b", "a"], (["a", "b"], ["a", "b"], [], [], True)),
    "disjoint": (["a"], ["b"], (["a", "b"], [], ["a"], ["a", "b"], False)),
    "duplicates": (["a", "a", "b"], ["b", "b"], (["a", "b"], ["b"], ["a"], ["a"], False)),
    "case": (["a"], ["A"], (["A", "a"], [], ["a"], ["A", "a"], False)),
}


@pytest.mark.parametrize("name", CASES)
def test_compare_sets(name):
    a, b, want = CASES[name]
    assert compare_sets(a, b) == want
compare_sets.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-set-operations/.

#include "compare_sets.hpp"

#include <algorithm>
#include <iterator>

// sort_unique makes a sorted vector with no repeats, which is the form that the
// set algorithms need.
static void sort_unique(std::vector<std::string> &v) {
    std::ranges::sort(v);
    auto repeats = std::ranges::unique(v);
    v.erase(repeats.begin(), repeats.end());
}

SetOps compare_sets(std::vector<std::string> a, std::vector<std::string> b) {
    sort_unique(a);
    sort_unique(b);
    SetOps r;
    std::ranges::set_union(a, b, std::back_inserter(r.either));
    std::ranges::set_intersection(a, b, std::back_inserter(r.both));
    std::ranges::set_difference(a, b, std::back_inserter(r.only_a));
    std::ranges::set_symmetric_difference(a, b, std::back_inserter(r.exactly_one));
    // includes(x, y) tells if y is in x, so the larger set comes first.
    r.a_in_b = std::ranges::includes(b, a);
    return r;
}
compare_sets.hpp 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-set-operations/.

#pragma once

#include <string>
#include <vector>

// SetOps has the results of the set operations. Each vector is in ascending
// order. The names are not union and so on, because union is a keyword.
struct SetOps {
    std::vector<std::string> either;      // the union
    std::vector<std::string> both;        // the intersection
    std::vector<std::string> only_a;      // the difference a minus b
    std::vector<std::string> exactly_one; // the symmetric difference
    bool a_in_b = false;                  // the set of a is a subset of the set of b

    bool operator==(const SetOps &) const = default;
};

// compare_sets does the set operations on the sets of a and b.
SetOps compare_sets(std::vector<std::string> a, std::vector<std::string> b);
test_compare_sets.cpp 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-set-operations/.

#include "compare_sets.hpp"

#include <iostream>
#include <string>
#include <string_view>
#include <vector>

static int failures = 0;

using Words = std::vector<std::string>;

static void check(std::string_view name, const Words &a, const Words &b, const SetOps &want) {
    if (compare_sets(a, b) != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("colors", Words{"red", "blue", "green"}, Words{"blue", "yellow"}, SetOps{Words{"blue", "green", "red", "yellow"}, Words{"blue"}, Words{"green", "red"}, Words{"green", "red", "yellow"}, false});
    check("subset", Words{"b"}, Words{"a", "b", "c"}, SetOps{Words{"a", "b", "c"}, Words{"b"}, Words{}, Words{"a", "c"}, true});
    check("both-empty", Words{}, Words{}, SetOps{Words{}, Words{}, Words{}, Words{}, true});
    check("empty-a", Words{}, Words{"x"}, SetOps{Words{"x"}, Words{}, Words{}, Words{"x"}, true});
    check("empty-b", Words{"x"}, Words{}, SetOps{Words{"x"}, Words{}, Words{"x"}, Words{"x"}, false});
    check("equal", Words{"a", "b"}, Words{"b", "a"}, SetOps{Words{"a", "b"}, Words{"a", "b"}, Words{}, Words{}, true});
    check("disjoint", Words{"a"}, Words{"b"}, SetOps{Words{"a", "b"}, Words{}, Words{"a"}, Words{"a", "b"}, false});
    check("duplicates", Words{"a", "a", "b"}, Words{"b", "b"}, SetOps{Words{"a", "b"}, Words{"b"}, Words{"a"}, Words{"a"}, false});
    check("case", Words{"a"}, Words{"A"}, SetOps{Words{"A", "a"}, Words{}, Words{"a"}, Words{"A", "a"}, false});
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
CompareSets.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-set-operations/.

import java.util.List;
import java.util.Set;
import java.util.TreeSet;

final class CompareSets {
  private CompareSets() {}

  /** The results of the set operations. Each list is in ascending order. */
  record Result(
      List<String> union,
      List<String> intersection,
      List<String> difference,
      List<String> symmetricDifference,
      boolean subset) {}

  static Result compareSets(List<String> a, List<String> b) {
    // A TreeSet keeps its items in order. String.compareTo compares UTF-16
    // code units, which is the byte order for ASCII.
    Set<String> setA = new TreeSet<>(a);
    Set<String> setB = new TreeSet<>(b);
    // addAll, retainAll and removeAll change the set, so each one works on a copy.
    Set<String> union = new TreeSet<>(setA);
    union.addAll(setB);
    Set<String> intersection = new TreeSet<>(setA);
    intersection.retainAll(setB);
    Set<String> difference = new TreeSet<>(setA);
    difference.removeAll(setB);
    Set<String> symmetric = new TreeSet<>(union);
    symmetric.removeAll(intersection);
    return new Result(
        List.copyOf(union),
        List.copyOf(intersection),
        List.copyOf(difference),
        List.copyOf(symmetric),
        setB.containsAll(setA));
  }
}
CompareSetsTest.java 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-set-operations/.

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class CompareSetsTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("colors", List.of("red", "blue", "green"), List.of("blue", "yellow"), new CompareSets.Result(List.of("blue", "green", "red", "yellow"), List.of("blue"), List.of("green", "red"), List.of("green", "red", "yellow"), false)),
        Arguments.of("subset", List.of("b"), List.of("a", "b", "c"), new CompareSets.Result(List.of("a", "b", "c"), List.of("b"), List.of(), List.of("a", "c"), true)),
        Arguments.of("both-empty", List.of(), List.of(), new CompareSets.Result(List.of(), List.of(), List.of(), List.of(), true)),
        Arguments.of("empty-a", List.of(), List.of("x"), new CompareSets.Result(List.of("x"), List.of(), List.of(), List.of("x"), true)),
        Arguments.of("empty-b", List.of("x"), List.of(), new CompareSets.Result(List.of("x"), List.of(), List.of("x"), List.of("x"), false)),
        Arguments.of("equal", List.of("a", "b"), List.of("b", "a"), new CompareSets.Result(List.of("a", "b"), List.of("a", "b"), List.of(), List.of(), true)),
        Arguments.of("disjoint", List.of("a"), List.of("b"), new CompareSets.Result(List.of("a", "b"), List.of(), List.of("a"), List.of("a", "b"), false)),
        Arguments.of("duplicates", List.of("a", "a", "b"), List.of("b", "b"), new CompareSets.Result(List.of("a", "b"), List.of("b"), List.of("a"), List.of("a"), false)),
        Arguments.of("case", List.of("a"), List.of("A"), new CompareSets.Result(List.of("A", "a"), List.of(), List.of("a"), List.of("A", "a"), false)));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void compareSets(String name, List<String> a, List<String> b, CompareSets.Result want) {
    assertEquals(want, CompareSets.compareSets(a, b));
  }
}
compare_sets.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-set-operations/.

#include "compare_sets.h"

#include <stdlib.h>
#include <string.h>

static int by_strcmp(const void *x, const void *y) {
    return strcmp(*(const char *const *)x, *(const char *const *)y);
}

void compare_sets(const char **a, size_t na, const char **b, size_t nb, struct set_ops *r) {
    // qsort needs a valid pointer even for 0 items, so skip it for short arrays.
    if (na > 1) {
        qsort(a, na, sizeof a[0], by_strcmp);
    }
    if (nb > 1) {
        qsort(b, nb, sizeof b[0], by_strcmp);
    }
    r->n_either = r->n_both = r->n_only_a = r->n_exactly_one = 0;
    r->a_in_b = true;
    // Walk the two sorted arrays together, like the merge step of merge sort.
    size_t i = 0;
    size_t j = 0;
    while (i < na || j < nb) {
        int c;
        if (i == na) {
            c = 1;
        } else if (j == nb) {
            c = -1;
        } else {
            c = strcmp(a[i], b[j]);
        }
        const char *word = c <= 0 ? a[i] : b[j];
        r->either[r->n_either++] = word;
        if (c == 0) {
            r->both[r->n_both++] = word;
        } else {
            r->exactly_one[r->n_exactly_one++] = word;
            if (c < 0) {
                r->only_a[r->n_only_a++] = word;
                r->a_in_b = false;
            }
        }
        // Skip the word and its repeats in both arrays.
        while (i < na && strcmp(a[i], word) == 0) {
            i++;
        }
        while (j < nb && strcmp(b[j], word) == 0) {
            j++;
        }
    }
}
compare_sets.h 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-set-operations/.

#ifndef COMPARE_SETS_H
#define COMPARE_SETS_H

#include <stdbool.h>
#include <stddef.h>

// set_ops has the results of the set operations. The caller gives the four
// arrays, each with room for na + nb pointers. compare_sets sets the counts.
struct set_ops {
    const char **either;      // the union
    size_t n_either;
    const char **both;        // the intersection
    size_t n_both;
    const char **only_a;      // the difference a minus b
    size_t n_only_a;
    const char **exactly_one; // the symmetric difference
    size_t n_exactly_one;
    bool a_in_b;              // the set of a is a subset of the set of b
};

// compare_sets sorts a and b in place by strcmp, then does the set operations
// on their words. Each result array is in ascending order with no repeats. The
// pointers in the results point to the strings of a and b.
void compare_sets(const char **a, size_t na, const char **b, size_t nb, struct set_ops *r);

#endif
test_compare_sets.c 58 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-set-operations/.

#include "compare_sets.h"

#include <stdio.h>
#include <string.h>

static int failures = 0;

// S makes a modifiable array of words and gives its length. An empty list is
// NULL, 0, because C has no empty array.
#define S(...) (const char *[]){__VA_ARGS__}, sizeof((const char *[]){__VA_ARGS__}) / sizeof(const char *)

enum { CAP = 16 };

// append adds the k words of xs, joined by commas, and then sep to buf.
static void append(char *buf, size_t size, const char *const *xs, size_t k, const char *sep) {
    for (size_t i = 0; i < k; i++) {
        size_t len = strlen(buf);
        snprintf(buf + len, size - len, "%s%s", i > 0 ? "," : "", xs[i]);
    }
    size_t len = strlen(buf);
    snprintf(buf + len, size - len, "%s", sep);
}

// check compares the results, joined as union|intersection|difference|symmetric|subset, with want.
static void check(const char *name, const char **a, size_t na, const char **b, size_t nb, const char *want) {
    const char *either[CAP], *both[CAP], *only_a[CAP], *exactly_one[CAP];
    struct set_ops r = {.either = either, .both = both, .only_a = only_a, .exactly_one = exactly_one};
    compare_sets(a, na, b, nb, &r);
    char got[256] = "";
    append(got, sizeof got, either, r.n_either, "|");
    append(got, sizeof got, both, r.n_both, "|");
    append(got, sizeof got, only_a, r.n_only_a, "|");
    append(got, sizeof got, exactly_one, r.n_exactly_one, r.a_in_b ? "|1" : "|0");
    if (strcmp(got, want) != 0) {
        fprintf(stderr, "case %s failed: got %s, want %s\n", name, got, want);
        failures++;
    }
}

int main(void) {
    check("colors", S("red", "blue", "green"), S("blue", "yellow"), "blue,green,red,yellow|blue|green,red|green,red,yellow|0");
    check("subset", S("b"), S("a", "b", "c"), "a,b,c|b||a,c|1");
    check("both-empty", NULL, 0, NULL, 0, "||||1");
    check("empty-a", NULL, 0, S("x"), "x|||x|1");
    check("empty-b", S("x"), NULL, 0, "x||x|x|0");
    check("equal", S("a", "b"), S("b", "a"), "a,b|a,b|||1");
    check("disjoint", S("a"), S("b"), "a,b||a|a,b|0");
    check("duplicates", S("a", "a", "b"), S("b", "b"), "a,b|b|a|a|0");
    check("case", S("a"), S("A"), "A,a||a|A,a|0");
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
CompareSets.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-set-operations/.

using System;
using System.Collections.Generic;
using System.Linq;

public static class CompareSets
{
    // Run returns the union, intersection, difference and symmetric difference
    // of the sets of a and b, each sorted, and whether the set of a is a subset
    // of the set of b.
    public static (string[] Union, string[] Intersection, string[] Difference, string[] SymmetricDifference, bool IsSubset)
        Run(IEnumerable<string> a, IEnumerable<string> b)
    {
        var setA = new HashSet<string>(a, StringComparer.Ordinal);
        var setB = new HashSet<string>(b, StringComparer.Ordinal);
        // UnionWith, IntersectWith, ExceptWith and SymmetricExceptWith change
        // the set, so each one works on a copy.
        var union = new HashSet<string>(setA, StringComparer.Ordinal);
        union.UnionWith(setB);
        var intersection = new HashSet<string>(setA, StringComparer.Ordinal);
        intersection.IntersectWith(setB);
        var difference = new HashSet<string>(setA, StringComparer.Ordinal);
        difference.ExceptWith(setB);
        var symmetric = new HashSet<string>(setA, StringComparer.Ordinal);
        symmetric.SymmetricExceptWith(setB);
        return (Sorted(union), Sorted(intersection), Sorted(difference), Sorted(symmetric), setA.IsSubsetOf(setB));
    }

    private static string[] Sorted(HashSet<string> set) => set.Order(StringComparer.Ordinal).ToArray();
}
CompareSetsTests.cs 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-set-operations/.

using Xunit;

public sealed class CompareSetsTests
{
    public static TheoryData<string, string[], string[], string[], string[], string[], string[], bool> Cases => new()
    {
        { "colors", new string[] { "red", "blue", "green" }, new string[] { "blue", "yellow" }, new string[] { "blue", "green", "red", "yellow" }, new string[] { "blue" }, new string[] { "green", "red" }, new string[] { "green", "red", "yellow" }, false },
        { "subset", new string[] { "b" }, new string[] { "a", "b", "c" }, new string[] { "a", "b", "c" }, new string[] { "b" }, new string[0], new string[] { "a", "c" }, true },
        { "both-empty", new string[0], new string[0], new string[0], new string[0], new string[0], new string[0], true },
        { "empty-a", new string[0], new string[] { "x" }, new string[] { "x" }, new string[0], new string[0], new string[] { "x" }, true },
        { "empty-b", new string[] { "x" }, new string[0], new string[] { "x" }, new string[0], new string[] { "x" }, new string[] { "x" }, false },
        { "equal", new string[] { "a", "b" }, new string[] { "b", "a" }, new string[] { "a", "b" }, new string[] { "a", "b" }, new string[0], new string[0], true },
        { "disjoint", new string[] { "a" }, new string[] { "b" }, new string[] { "a", "b" }, new string[0], new string[] { "a" }, new string[] { "a", "b" }, false },
        { "duplicates", new string[] { "a", "a", "b" }, new string[] { "b", "b" }, new string[] { "a", "b" }, new string[] { "b" }, new string[] { "a" }, new string[] { "a" }, false },
        { "case", new string[] { "a" }, new string[] { "A" }, new string[] { "A", "a" }, new string[0], new string[] { "a" }, new string[] { "A", "a" }, false },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, string[] a, string[] b, string[] union, string[] intersection, string[] difference, string[] symmetric, bool isSubset)
    {
        Assert.NotNull(name);
        var got = CompareSets.Run(a, b);
        Assert.Equal(union, got.Union);
        Assert.Equal(intersection, got.Intersection);
        Assert.Equal(difference, got.Difference);
        Assert.Equal(symmetric, got.SymmetricDifference);
        Assert.Equal(isSubset, got.IsSubset);
    }
}
compare_sets.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-set-operations/.

/**
 * Returns the union, intersection, difference and symmetric difference of the
 * sets of a and b, each sorted, and whether the set of a is a subset of the set of b.
 * @param {string[]} a
 * @param {string[]} b
 * @returns {[string[], string[], string[], string[], boolean]}
 */
export function compareSets(a, b) {
  const setA = new Set(a);
  const setB = new Set(b);
  // The default sort compares UTF-16 code units, which is the byte order for ASCII.
  const sorted = (s) => [...s].sort();
  return [
    sorted(setA.union(setB)),
    sorted(setA.intersection(setB)),
    sorted(setA.difference(setB)),
    sorted(setA.symmetricDifference(setB)),
    setA.isSubsetOf(setB),
  ];
}
compare_sets.test.js 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-set-operations/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { compareSets } from "./compare_sets.js";

const cases = [
  ["colors", ["red", "blue", "green"], ["blue", "yellow"], [["blue", "green", "red", "yellow"], ["blue"], ["green", "red"], ["green", "red", "yellow"], false]],
  ["subset", ["b"], ["a", "b", "c"], [["a", "b", "c"], ["b"], [], ["a", "c"], true]],
  ["both-empty", [], [], [[], [], [], [], true]],
  ["empty-a", [], ["x"], [["x"], [], [], ["x"], true]],
  ["empty-b", ["x"], [], [["x"], [], ["x"], ["x"], false]],
  ["equal", ["a", "b"], ["b", "a"], [["a", "b"], ["a", "b"], [], [], true]],
  ["disjoint", ["a"], ["b"], [["a", "b"], [], ["a"], ["a", "b"], false]],
  ["duplicates", ["a", "a", "b"], ["b", "b"], [["a", "b"], ["b"], ["a"], ["a"], false]],
  ["case", ["a"], ["A"], [["A", "a"], [], ["a"], ["A", "a"], false]],
];

for (const [name, a, b, want] of cases) {
  test(name, () => {
    assert.deepEqual(compareSets(a, b), want);
  });
}
compare_sets.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-set-operations/.

export type SetOps = [string[], string[], string[], string[], boolean];

// compareSets returns the union, intersection, difference and symmetric
// difference of the sets of a and b, each sorted, and whether the set of a is a
// subset of the set of b.
export function compareSets(a: readonly string[], b: readonly string[]): SetOps {
  const setA = new Set(a);
  const setB = new Set(b);
  // The default sort compares UTF-16 code units, which is the byte order for ASCII.
  const sorted = (s: Set<string>): string[] => [...s].sort();
  return [
    sorted(setA.union(setB)),
    sorted(setA.intersection(setB)),
    sorted(setA.difference(setB)),
    sorted(setA.symmetricDifference(setB)),
    setA.isSubsetOf(setB),
  ];
}
compare_sets.test.ts 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-set-operations/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { compareSets, type SetOps } from "./compare_sets.ts";

const cases: [string, string[], string[], SetOps][] = [
  ["colors", ["red", "blue", "green"], ["blue", "yellow"], [["blue", "green", "red", "yellow"], ["blue"], ["green", "red"], ["green", "red", "yellow"], false]],
  ["subset", ["b"], ["a", "b", "c"], [["a", "b", "c"], ["b"], [], ["a", "c"], true]],
  ["both-empty", [], [], [[], [], [], [], true]],
  ["empty-a", [], ["x"], [["x"], [], [], ["x"], true]],
  ["empty-b", ["x"], [], [["x"], [], ["x"], ["x"], false]],
  ["equal", ["a", "b"], ["b", "a"], [["a", "b"], ["a", "b"], [], [], true]],
  ["disjoint", ["a"], ["b"], [["a", "b"], [], ["a"], ["a", "b"], false]],
  ["duplicates", ["a", "a", "b"], ["b", "b"], [["a", "b"], ["b"], ["a"], ["a"], false]],
  ["case", ["a"], ["A"], [["A", "a"], [], ["a"], ["A", "a"], false]],
];

for (const [name, a, b, want] of cases) {
  test(name, () => {
    assert.deepEqual(compareSets(a, b), want);
  });
}
compare_sets.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-set-operations/.

// Package compare does set operations on two lists of words.
package compare

import (
	"maps"
	"slices"
)

// Result has the results of the set operations. Each slice is in ascending
// order.
type Result struct {
	Union, Intersection, Difference, SymmetricDifference []string
	Subset                                               bool
}

type set map[string]struct{}

func newSet(words []string) set {
	s := make(set, len(words))
	for _, w := range words {
		s[w] = struct{}{}
	}
	return s
}

func (s set) has(w string) bool {
	_, ok := s[w]
	return ok
}

// CompareSets returns the union, intersection, difference and symmetric
// difference of the sets of a and b, and whether the set of a is a subset of
// the set of b.
func CompareSets(a, b []string) Result {
	// Go has no set type and no set operations, so each one is a loop.
	sa, sb := newSet(a), newSet(b)
	union, inter, diff, sym := set{}, set{}, set{}, set{}
	for w := range sa {
		union[w] = struct{}{}
		if sb.has(w) {
			inter[w] = struct{}{}
		} else {
			diff[w] = struct{}{}
			sym[w] = struct{}{}
		}
	}
	for w := range sb {
		if !sa.has(w) {
			union[w] = struct{}{}
			sym[w] = struct{}{}
		}
	}
	sorted := func(s set) []string { return slices.Sorted(maps.Keys(s)) }
	return Result{sorted(union), sorted(inter), sorted(diff), sorted(sym), len(diff) == 0}
}
compare_sets_test.go 40 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-set-operations/.

package compare

import (
	"slices"
	"testing"
)

var cases = []struct {
	name string
	a, b []string
	want Result
}{
	{"colors", []string{"red", "blue", "green"}, []string{"blue", "yellow"}, Result{[]string{"blue", "green", "red", "yellow"}, []string{"blue"}, []string{"green", "red"}, []string{"green", "red", "yellow"}, false}},
	{"subset", []string{"b"}, []string{"a", "b", "c"}, Result{[]string{"a", "b", "c"}, []string{"b"}, []string{}, []string{"a", "c"}, true}},
	{"both-empty", []string{}, []string{}, Result{[]string{}, []string{}, []string{}, []string{}, true}},
	{"empty-a", []string{}, []string{"x"}, Result{[]string{"x"}, []string{}, []string{}, []string{"x"}, true}},
	{"empty-b", []string{"x"}, []string{}, Result{[]string{"x"}, []string{}, []string{"x"}, []string{"x"}, false}},
	{"equal", []string{"a", "b"}, []string{"b", "a"}, Result{[]string{"a", "b"}, []string{"a", "b"}, []string{}, []string{}, true}},
	{"disjoint", []string{"a"}, []string{"b"}, Result{[]string{"a", "b"}, []string{}, []string{"a"}, []string{"a", "b"}, false}},
	{"duplicates", []string{"a", "a", "b"}, []string{"b", "b"}, Result{[]string{"a", "b"}, []string{"b"}, []string{"a"}, []string{"a"}, false}},
	{"case", []string{"a"}, []string{"A"}, Result{[]string{"A", "a"}, []string{}, []string{"a"}, []string{"A", "a"}, false}},
}

func TestCompareSets(t *testing.T) {
	for _, c := range cases {
		got := CompareSets(c.a, c.b)
		// slices.Equal treats a nil slice and an empty slice as equal.
		ok := slices.Equal(got.Union, c.want.Union) &&
			slices.Equal(got.Intersection, c.want.Intersection) &&
			slices.Equal(got.Difference, c.want.Difference) &&
			slices.Equal(got.SymmetricDifference, c.want.SymmetricDifference) &&
			got.Subset == c.want.Subset
		if !ok {
			t.Errorf("%s: got %+v, want %+v", c.name, got, c.want)
		}
	}
}
compare_sets.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-set-operations/.

use std::collections::BTreeSet;

/// The results of the set operations. Each vector is in ascending order.
#[derive(Debug, PartialEq)]
pub struct SetOps<'a> {
    pub union: Vec<&'a str>,
    pub intersection: Vec<&'a str>,
    pub difference: Vec<&'a str>,
    pub symmetric_difference: Vec<&'a str>,
    pub is_subset: bool,
}

/// Returns the union, intersection, difference and symmetric difference of the
/// sets of a and b, and whether the set of a is a subset of the set of b.
pub fn compare_sets<'a>(a: &[&'a str], b: &[&'a str]) -> SetOps<'a> {
    // A BTreeSet visits its items in ascending order, so no sort is needed.
    let sa: BTreeSet<&'a str> = a.iter().copied().collect();
    let sb: BTreeSet<&'a str> = b.iter().copied().collect();
    SetOps {
        union: sa.union(&sb).copied().collect(),
        intersection: sa.intersection(&sb).copied().collect(),
        difference: sa.difference(&sb).copied().collect(),
        symmetric_difference: sa.symmetric_difference(&sb).copied().collect(),
        is_subset: sa.is_subset(&sb),
    }
}
tests/compare_sets_test.rs 67 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-set-operations/.

use algo_do_set_operations::{compare_sets, SetOps};

#[test]
fn cases() {
    let cases: Vec<(&str, Vec<&str>, Vec<&str>, SetOps)> = vec![
        (
            "colors",
            vec!["red", "blue", "green"],
            vec!["blue", "yellow"],
            SetOps { union: vec!["blue", "green", "red", "yellow"], intersection: vec!["blue"], difference: vec!["green", "red"], symmetric_difference: vec!["green", "red", "yellow"], is_subset: false },
        ),
        (
            "subset",
            vec!["b"],
            vec!["a", "b", "c"],
            SetOps { union: vec!["a", "b", "c"], intersection: vec!["b"], difference: vec![], symmetric_difference: vec!["a", "c"], is_subset: true },
        ),
        (
            "both-empty",
            vec![],
            vec![],
            SetOps { union: vec![], intersection: vec![], difference: vec![], symmetric_difference: vec![], is_subset: true },
        ),
        (
            "empty-a",
            vec![],
            vec!["x"],
            SetOps { union: vec!["x"], intersection: vec![], difference: vec![], symmetric_difference: vec!["x"], is_subset: true },
        ),
        (
            "empty-b",
            vec!["x"],
            vec![],
            SetOps { union: vec!["x"], intersection: vec![], difference: vec!["x"], symmetric_difference: vec!["x"], is_subset: false },
        ),
        (
            "equal",
            vec!["a", "b"],
            vec!["b", "a"],
            SetOps { union: vec!["a", "b"], intersection: vec!["a", "b"], difference: vec![], symmetric_difference: vec![], is_subset: true },
        ),
        (
            "disjoint",
            vec!["a"],
            vec!["b"],
            SetOps { union: vec!["a", "b"], intersection: vec![], difference: vec!["a"], symmetric_difference: vec!["a", "b"], is_subset: false },
        ),
        (
            "duplicates",
            vec!["a", "a", "b"],
            vec!["b", "b"],
            SetOps { union: vec!["a", "b"], intersection: vec!["b"], difference: vec!["a"], symmetric_difference: vec!["a"], is_subset: false },
        ),
        (
            "case",
            vec!["a"],
            vec!["A"],
            SetOps { union: vec!["A", "a"], intersection: vec![], difference: vec!["a"], symmetric_difference: vec!["A", "a"], is_subset: false },
        ),
    ];
    for (name, a, b, want) in cases {
        assert_eq!(compare_sets(&a, &b), want, "{name}");
    }
}
compare_sets.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/do-set-operations/.

# compare_sets A_WORD... -- B_WORD...
# Prints five lines: the union, the intersection, the difference and the
# symmetric difference of the two sets, each in ascending order by bytes with
# the words split by spaces, and then true if the set of A is a subset of the
# set of B, else false.
compare_sets() {
  # Bash has no set type. The keys of an associative array are the set.
  local -A in_a=() in_b=()
  local word
  while (($# > 0)) && [[ $1 != -- ]]; do
    in_a[$1]=1
    shift
  done
  shift # the --
  for word in "$@"; do
    in_b[$word]=1
  done
  local -a either=() both=() only_a=() one=()
  local subset=true
  for word in "${!in_a[@]}"; do
    either+=("$word")
    if [[ -v in_b[$word] ]]; then
      both+=("$word")
    else
      only_a+=("$word")
      one+=("$word")
      subset=false
    fi
  done
  for word in "${!in_b[@]}"; do
    if [[ ! -v in_a[$word] ]]; then
      either+=("$word")
      one+=("$word")
    fi
  done
  _sorted_line "${either[@]}"
  _sorted_line "${both[@]}"
  _sorted_line "${only_a[@]}"
  _sorted_line "${one[@]}"
  echo "$subset"
}

# _sorted_line WORD...
# Prints the words in ascending order by bytes on one line.
_sorted_line() {
  if (($# == 0)); then
    echo
    return
  fi
  printf '%s\n' "$@" | LC_ALL=C sort | paste -sd ' ' -
}
test_compare_sets.bats 29 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/do-set-operations/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/compare_sets.sh"
}

check() { # check WANT ARG...
  local want got
  # %b turns each \n in WANT into a newline. The x keeps the trailing
  # newlines, which $(...) removes.
  want=$(printf '%b' "$1"; printf x)
  shift
  got=$(compare_sets "$@"; printf x)
  [ "$got" = "$want" ] || { printf 'got:  %q\nwant: %q\n' "$got" "$want"; return 1; }
}

@test "colors" { check "blue green red yellow\nblue\ngreen red\ngreen red yellow\nfalse\n" red blue green -- blue yellow; }
@test "subset" { check "a b c\nb\n\na c\ntrue\n" b -- a b c; }
@test "both-empty" { check "\n\n\n\ntrue\n" --; }
@test "empty-a" { check "x\n\n\nx\ntrue\n" -- x; }
@test "empty-b" { check "x\n\nx\nx\nfalse\n" x --; }
@test "equal" { check "a b\na b\n\n\ntrue\n" a b -- b a; }
@test "disjoint" { check "a b\n\na\na b\nfalse\n" a -- b; }
@test "duplicates" { check "a b\nb\na\na\nfalse\n" a a b -- b b; }
@test "case" { check "A a\n\na\nA a\nfalse\n" a -- A; }

References

  1. The Python Standard Library, Set Types, set and frozenset methods
  2. MDN Web Docs, Set, Set composition; Instance methods
  3. .NET API reference, HashSet<T> class, Methods
  4. Java SE 25 API, Interface Set, retainAll
  5. Go standard library, package maps, func Equal
  6. Rust standard library, struct HashSet, difference
  7. cppreference.com, std::includes, Description
  8. cppreference.com, Logical operators (C), Logical AND
  9. Bash Reference Manual, 6.7 Arrays

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source