Volume 1 Companion: Foundations of ComputingPractice for Volume 1
0 / 0

Workbench / Volume 1 Companion: Foundations of Computing

V1·05

Discrete Mathematics

Companion to Volume 1, chapter 05: how sets, logic and counting connect; new angles (sorting laundry as equivalence classes, a light-switch panel as a bitset, dominoes and a staircase for induction, airport security for Bayes); what the chapter simplifies, from two Java sets that are equal in one direction only to a "customers who never ordered" query that returns nobody, and the theory behind it (relations against SQL's bags, why some problems can't be computed, sparse road graphs, proof against testing); the JDK's EnumSet and Random source, including predicting Random's next number from two outputs; four debugging drills; interview questions with how to approach each.

6 sections · ~17 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 05 has three strands. Sets, relations and functions are the vocabulary of data: collections, how items relate, and mappings between them. Logic and proof are the vocabulary of conditions and correctness. Counting and chance are the vocabulary of how many, and how likely.

sets, relations, functions logic and proof counting and chance sets membership · no order bitsets a set as bits of a word relations sets of pairs equivalence relations equals(), grouping order relations compareTo, sorting functions injective · pigeonhole propositional logic and · or · not · implies Boolean algebra laws · normal forms quantifiers for all · there exists proof techniques direct · contradiction induction base + step loop invariants induction for code counting product · permutations probability events · independence Bayes, expectation update · average birthday bound collisions at √N recurrences cost of recursion graphs and trees relations drawn as bits partition or rank laws over sets claims for all n in code ÷ total update applied trees of calls AND = ∩ ∩ is and goes deeper: ch4 recurrences and graph algorithms · ch6 modular arithmetic · ch10 grammars Volume 4: relational algebra and SQL's three-valued logic · Volume 5: probability of failure
Concept map of chapter 05: sets, relations and functions (sets and bitsets, relations, equivalence and order relations, functions and the pigeonhole principle), logic and proof (propositional logic, Boolean algebra, quantifiers, proof techniques, induction and loop invariants), and counting and chance (combinatorics, probability, Bayes, expectation, the birthday bound, recurrences, graphs and trees), with links such as equals() having to be an equivalence relation and loop invariants being induction applied to code.

The links worth remembering:

  • Set operations and logic are the same algebra. Intersection is AND, union is OR, complement is NOT, and a bitset makes it literal: one machine instruction per 64 members. That's why EnumSet is fast (Code walkthrough) and why feature-flag rules can be simplified with Boolean laws.
  • equals and compareTo are relations, with contracts. equals must be an equivalence relation; compareTo must be a total order. When they disagree, collections built on one or the other disagree too (Gaps 1 and 2).
  • Induction is the proof behind every loop and every recursive function. A loop invariant is induction over iterations; structural induction is induction over a recursive data type.

Explain it differently

1. An equivalence relation is sorting laundry. "Same colour" splits a pile into heaps: every sock is in exactly one heap, a sock is the same colour as itself, and if A matches B and B matches C, A matches C. Those three rules (reflexive, symmetric, transitive) are what guarantee clean heaps. Try sorting by "similar colour" instead and the heaps blur: light grey matches grey, grey matches charcoal, but light grey doesn't match charcoal, so which heap does grey go in? Chapter Exercises P3 shows that with prices. equals must be a "same colour" relation, never a "similar colour" one.

2. A bitset is a panel of light switches. A row of 64 switches, one per permission (view, edit, refund, …). A user's permissions are which switches are on. "Does this user have all of these permissions?" is "lay the required pattern over the panel and check nothing required is off": one AND and one comparison, whatever the number of permissions. That's containsAll in RegularEnumSet, line for line (Code walkthrough).

3. Induction is a staircase you can always climb. If you can reach the first step, and from any step you can always reach the next, you can reach every step, however high. You never climb them all to know. A loop invariant is the same: true before the first iteration, kept by every iteration, so true when the loop ends. Strong induction lets you stand on all the steps below, not just the previous one, which is what recursive algorithms on trees need.

4. Logic laws are rewriting a restaurant's rules. "No entry unless you have a booking or you're a member, and not if the kitchen is closed" can be written a dozen ways. De Morgan's laws, distribution and absorption are the rules for rewriting it without changing who gets in. Every refactor of an if condition is a claim that two Boolean expressions are equal, and with k variables there are only 2^k cases to check (Chapter Exercises P2 checks them all).

5. Bayes is airport security. The scanner beeps for 99% of people carrying a knife and for 2% of people who aren't. Almost no one carries a knife (say 1 in 100,000). So of everyone who beeps, how many have one? About 1 in 2,000: the 2% of honest passengers is a huge crowd next to the tiny number of real cases. Every fraud alert, error-rate alarm and "the test says it's flaky" judgement has this shape: the rarer the real thing, the more of your alarms are false.

6. Counting is the thali menu. 4 rice options × 6 curries × 3 desserts = 72 thalis (product rule). Choose any 3 curries from 6 without caring about order: C(6, 3) = 20. In order: 6 × 5 × 4 = 120. The same counting tells you how many test cases "all combinations" means (exponential), how many IDs fit in 8 characters, and how long a brute-force guess takes.

7. A function is a vending machine; the pigeonhole principle is its limit. Each button gives exactly one snack (a function). Different buttons giving different snacks is injective; every snack being on some button is surjective. If there are more buttons than snacks, some snack is behind two buttons, however clever the wiring. That's the pigeonhole principle, and it's why every hash function with a fixed-size output has collisions: String.hashCode maps unlimited strings to 2³² values.

8. Mod is a clock, but programming languages disagree about which clock. 7 hours before 3 o'clock is 8 o'clock: on a clock, −7 mod 12 lands in 0…11. Python agrees (-7 % 3 is 2). Java and C don't: -7 % 3 is −1, because % there is a remainder, taking the sign of the dividend. Any code that turns a hash (which can be negative) into a bucket, shard or array index has to know which clock it's on (drill D1).

Gaps and misconceptions

What the chapter oversimplifies

1. "equals() must be an equivalence relation": and then two collections break symmetry anyway. The chapter states the contract for one class. Collections compose classes, and the contract can break between them. A TreeSet with a case-insensitive comparator against a HashSet (real output, JDK 21):

Terminal
treeSet.equals(hashSet) = true, hashSet.equals(treeSet) = false

Both inherit AbstractSet.equals, which checks the sizes and then calls this.containsAll(other): "do I contain each of your elements?", answered by my own lookup. The TreeSet looks up "RAVI@tiffin.in" with its case-insensitive comparator and finds "ravi@tiffin.in": true. The HashSet looks up "ravi@tiffin.in" with equals and doesn't find it: false. Equality isn't symmetric, so assertEquals(expected, actual) can pass while assertEquals(actual, expected) fails, and a set of sets can hold "duplicates". The rule: within a program, pick one notion of sameness per kind of value (normalise emails to lower case at the boundary), rather than letting each collection pick its own.

2. "Order relations: compareTo" and "equivalence: equals" can disagree, and both are legal. BigDecimal is the famous example:

Terminal
HashSet of 2.0, 2.00, 2: size 3 | TreeSet: size 1 | 2.0 equals 2.00? false | compareTo = 0

equals says 2.0 and 2.00 are different (scale is part of the value); compareTo says they're equal. So a HashSet holds three "twos" and a TreeSet holds one. The Javadoc calls such a class "inconsistent with equals", and it's allowed. Neither is wrong; they're two different relations, and the collection you choose decides which one applies. This is why TiffinBox keeps money as integer paise (stage 2): one representation per amount, so the two relations can't disagree.

3. "SQL uses three-valued logic": the dangerous case is NOT IN, not <>. The chapter shows WHERE x <> 5 skipping NULL rows. The same logic turns a common query into one that silently returns nothing. Real output, PostgreSQL 16, three customers, and one order whose customer_id is NULL:

Terminal
 never_ordered_not_in
----------------------
(0 rows)

 never_ordered_not_exists
--------------------------
                        2
                        3
(2 rows)

3 NOT IN (1, NULL) means 3 <> 1 AND 3 <> NULL, which is TRUE AND UNKNOWN, which is UNKNOWN, so the row is filtered out. One NULL in the subquery makes NOT IN return no rows for anyone. NOT EXISTS doesn't have this problem, because it asks whether a matching row exists, which is a plain true or false. Classical logic's law of excluded middle (every statement is true or false) doesn't hold in SQL, and the textbook rewrite NOT EXISTS ⇔ NOT IN is valid only when NULLs can't occur.

4. "Floats: NaN ≠ NaN" is one of three different equalities. The chapter notes NaN breaks reflexivity. In Java there are actually two equalities on doubles, and they disagree on two values:

Terminal
NaN == NaN: false, Double.valueOf(NaN).equals(NaN): true, 0.0 == -0.0: true, Double.valueOf(0.0).equals(-0.0): false

== follows IEEE 754 (NaN equals nothing; 0.0 and −0.0 are equal). Double.equals compares bit patterns, so that Double can be a well-behaved key in a HashMap (reflexive again), at the cost of separating 0.0 and −0.0. Python has a third behaviour: nan in [nan] is True for the same object (containment checks identity first) and False for two separate NaNs. Rule: never use floating-point values as keys or for equality-based grouping.

Common misconceptions

Misconception What's actually true Where it's shown
"x % n is always in 0…n−1." In Java, C, C++, Go and Rust it's negative for negative x. Use Math.floorMod. drill D1
"Math.abs returns a non-negative number." Math.abs(Integer.MIN_VALUE) is Integer.MIN_VALUE: there's no positive 2³¹ in an int. drill D1
"NOT IN and NOT EXISTS are the same." Only when the subquery can't produce NULL. Gaps 3; drill D3
"A join just adds columns." A join of relations multiplies rows when keys repeat: customer 1 with 2 orders becomes 2 rows, and SUM after the join double-counts. drill D3
"java.util.Random is random enough for tokens." It's a public recurrence; two outputs predict the third. Code walkthrough
"Passing 1,000 random tests proves it." It's evidence about the cases tried. Exhaustive checking of a finite space, or a proof, says something about all cases. theoretical gap 4; TiffinBox build, stage 5

Theoretical gaps: the ideas behind the chapter

1. Tables are relations; SQL results are not quite. A relation in the chapter is a set of pairs; a database table is a relation of n-tuples, which is where the "relational" model gets its name (Codd, 1970). But SQL works with bags (multisets): SELECT customer_id FROM orders returns duplicates, UNION ALL keeps them, and only DISTINCT or UNION gives a set. Joins are the relational composition of relations, which is why they multiply rows when a key repeats (drill D3). Knowing whether you're holding a set or a bag at each step of a query is half of writing correct reports (Interview prep Q5).

2. There are more problems than programs, so some can't be solved. Programs are finite strings over a finite alphabet, so they can be listed: program 1, program 2, … (they're countable). Yes/no questions about natural numbers ("is n in the set?") correspond to infinite subsets of ℕ, and Cantor's diagonal argument shows those can't be listed. So most such questions have no program that answers them. The halting problem (chapter 01's companion) is one concrete example. The same diagonal argument proves there are more real numbers than integers, which is a reason floats can only approximate (chapter 6).

3. Road networks are sparse for a reason: planarity. Chapter 03 said real graphs are sparse. For planar graphs (drawable without crossings, roughly what a road map is), Euler's formula V − E + F = 2 implies E ≤ 3V − 6 for V ≥ 3. So a city of a million junctions has at most about 3 million roads, never 10¹² pairs. That's the mathematical reason adjacency lists win, and why Dijkstra on a city runs in near-linear time (TiffinBox build, stage 4).

4. Proof, exhaustive check and testing are three different claims. A test checks chosen cases. An exhaustive check covers every case of a finite model (every state × event pair, every history up to length 6), which is a proof by cases of the model, though not of reality. A proof covers infinitely many cases (all n, all inputs) by reasoning. Dijkstra's line, "testing shows the presence, not the absence, of bugs", is about the first. The TiffinBox build's stage 5 uses the second, and found a real bug that every example test missed.

5. Functions in mathematics are total and pure; functions in code often aren't. The chapter defines a function as mapping every domain element to exactly one value. Code "functions" can be partial (they throw or loop forever for some inputs: Integer.parseInt("abc")), and impure (different results for the same input: Instant.now()). Typed functional programming tries to close the gap: Optional and result types make partiality visible in the type, and keeping I/O at the edges keeps the core pure. That's stage 2's rule "no clock in core/", seen from mathematics.

6. Modular arithmetic is the algebra under hashing, randomness and cryptography. Integers mod n form a ring: you can add, subtract and multiply and stay inside 0…n−1. java.util.Random is a linear congruential generator, a recurrence x_{k+1} = (a·x_k + c) mod 2⁴⁸ (Code walkthrough); hash tables use mod (or a mask) to pick buckets; RSA and Diffie–Hellman are exponentiation mod n. The chapter's recurrences and this algebra together explain why Random is predictable: a linear recurrence with known constants can be run forward by anyone.

Applying it

Code walkthrough

Two small JDK classes put the chapter's mathematics directly into code. Excerpts from jdk-21-ga.

RegularEnumSet: set algebra as bit operations

java/util/RegularEnumSet.java is what EnumSet.of(…) returns for enums with at most 64 constants. The whole set is one field:

Java
    private long elements = 0L;

Bit i is set when the constant with ordinal i is a member. Membership and insertion:

Java
    public boolean contains(Object e) {
        if (e == null)
            return false;
        Class<?> eClass = e.getClass();
        if (eClass != elementType && eClass.getSuperclass() != elementType)
            return false;

        return (elements & (1L << ((Enum<?>)e).ordinal())) != 0;
    }

    public boolean add(E e) {
        typeCheck(e);

        long oldElements = elements;
        elements |= (1L << ((Enum<?>)e).ordinal());
        return elements != oldElements;
    }

And subset, the chapter's A ⊆ B, as one expression:

Java
    public boolean containsAll(Collection<?> c) {
        if (!(c instanceof RegularEnumSet<?> es))
            return super.containsAll(c);

        if (es.elementType != elementType)
            return es.isEmpty();

        return (es.elements & ~elements) == 0;
    }

Read (es.elements & ~elements) == 0 as set algebra: ~elements is the complement of this set; ANDing gives the members of es that are not in this set (B ∖ A); and "that's empty" is exactly "B ⊆ A". Three laws from the chapter, one instruction each. Two details:

  • contains checks eClass.getSuperclass() != elementType because enum constants with their own bodies (PENDING { … }) are anonymous subclasses of the enum.
  • add returns whether the set changed by comparing the old and new words, with no separate contains check.

So EnumSet<Permission> is both the safest and the fastest way to hold permissions: type-checked, and as cheap as hand-written bit masks. (Chapter Exercises P1 builds bitset permissions by hand.)

Random: a recurrence, and why it isn't secret

java/util/Random.java:

Java
    private static final long multiplier = 0x5DEECE66DL;
    private static final long addend = 0xBL;
    private static final long mask = (1L << 48) - 1;

    protected int next(int bits) {
        long oldseed, nextseed;
        AtomicLong seed = this.seed;
        do {
            oldseed = seed.get();
            nextseed = (oldseed * multiplier + addend) & mask;
        } while (!seed.compareAndSet(oldseed, nextseed));
        return (int)(nextseed >>> (48 - bits));
    }

The state is a 48-bit number. Each step is the recurrence seed′ = (seed × 0x5DEECE66D + 11) mod 2⁴⁸ (the & mask is the mod), and nextInt() returns the top 32 of those 48 bits. So one output reveals 32 of the 48 bits of state, and the other 16 can be guessed: there are only 2¹⁶ = 65,536 possibilities, and the second output tells you which guess was right. A short program doing exactly that (real output):

Terminal
java.util.Random: saw -809391686, 758859162; predicted next 1049251505, actual 1049251505

Two outputs, then every future output, in a fraction of a second. That's not a bug in Random: it's a fast, well-distributed generator for simulations and shuffling, and its Javadoc says it isn't cryptographically secure. It's the reason order codes, password-reset tokens and idempotency keys must come from SecureRandom or a cryptographic hash (the TiffinBox build, stage 5). The compareAndSet loop, by the way, makes it thread-safe but contended under many threads, which is why ThreadLocalRandom exists.

Read it yourself

  1. Write retainAll (A ← A ∩ B) for two RegularEnumSets as one line, and removeAll (A ← A ∖ B).
  2. Why does Random keep 48 bits of state but return only 32?

Debugging drills

D1. One customer's orders crash the shard router

Orders are routed to one of 10 database shards with shards[Math.abs(key.hashCode()) % 10]. It worked for a year, then one customer key started failing:

Terminal
Math.abs(hash) % 10 = -8, Math.floorMod(hash, 10) = 2
java.lang.ArrayIndexOutOfBoundsException: Index -8 out of bounds for length 10

The key was "polygenelubricants". Explain, and fix it.

D2. A price list that "de-duplicates" differently on two screens

The admin screen shows distinct prices from a HashSet<BigDecimal>; the export uses a TreeSet<BigDecimal>. For prices entered as "2.0", "2.00" and "2":

Terminal
HashSet of 2.0, 2.00, 2: size 3 | TreeSet: size 1 | 2.0 equals 2.00? false | compareTo = 0

Which is right, and how do you make them agree?

D3. "Customers who never ordered": zero, after a data import

A marketing report runs:

SQL
SELECT id FROM customers WHERE id NOT IN (SELECT customer_id FROM orders);

It returned a few thousand customers each week, then zero after an import of guest-checkout orders. The real reproduction (three customers, two orders from customer 1, one guest order with customer_id NULL):

Terminal
 never_ordered_not_in
----------------------
(0 rows)

Explain, fix it, and say what other report in the same codebase is likely double-counting.

D4. A test that passes or fails depending on argument order

Java
Set<String> expected = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);   // built from config
expected.addAll(List.of("asha@tiffin.in", "ravi@tiffin.in"));
Set<String> actual = service.notifiedEmails();                         // a HashSet: {"asha@tiffin.in", "RAVI@tiffin.in"}
assertEquals(expected, actual);   // passes
assertEquals(actual, expected);   // fails
Terminal
treeSet.equals(hashSet) = true, hashSet.equals(treeSet) = false

Which one is telling the truth, and what's the real bug?

Career-oriented

Interview prep

Mid level

Q1. Explain ==, equals and compareTo in Java as mathematical relations, and say when each is the right one to use.

How to get there. Name the relation each one is (identity; an equivalence relation; a total order), state the contract, then give one case where they disagree and what breaks. Interviewers are checking that you know collections pick one of them for you.

Q2. Write a function that removes duplicates from a sorted array in place and returns the new length. Then state its loop invariant.

How to get there. Write the two-pointer solution, then state the invariant in terms of the prefix the function has built, and show initialisation, maintenance and termination. Interviewers want to see that you can explain why it's right, not just that it passes.

Senior level

Q3. The discount engine has 40 rules written by different teams, and customers sometimes get two discounts that were meant to be exclusive. How do you find conflicting rules before they ship?

How to get there. Recognise that each rule's condition is a logical formula over facts about the order, and "two rules can both fire" is satisfiability of their conjunction. Then match the technique to the size: brute force over small finite domains, a SAT/SMT solver for larger ones, and process changes so conflicts are checked in CI.

Q4. Design order IDs for TiffinBox: unique across 20 servers, roughly sortable by time, short enough to read out on a phone call, and not guessable. Justify the bits.

How to get there. These requirements conflict, so allocate bits to each and do the counting. Separate the internal ID (sortable, unique) from the customer-facing code (short, unguessable), or show why one ID can do both.

Staff level

Q5. Finance's monthly revenue report and the application's dashboard disagree by 3%, and each team trusts its own. How do you resolve it?

How to get there. Treat it as a definitions problem first (which orders, which money, which time zone), then a query semantics problem (NULLs, joins multiplying rows, set against bag), then an organisational one (one owned definition). Make the reconciliation reproducible.

Q6. When is a correctness argument worth a formal proof or an exhaustive check, rather than ordinary tests? Give examples from a food-delivery system.

How to get there. Weigh cost of being wrong against cost of the method, and match the method to the shape of the problem: small finite state spaces suit exhaustive checking; concurrency and distribution suit model checking; algorithms with crisp specs suit property tests; most CRUD suits examples.