Bit Vector

Context: FIT1008_MOC · the representation behind BVSet · realises a Set (ADT) with bitwise ops · a Data Structure

Quick Revision

  • 🎯 Objective: store small non-negative integers as the bits of an integer ➔ bit set ⟺ item present (the characteristic function).
  • 📦 Core Components: bitwise member/add/remove ➔ word-parallel algebra ➔ popcount for size.
  • ⚡ Key Constraint: ops, algebra — cost scales with the universe (max value), not the count.

📝 Core

1. The Bit Vector (Bits = Set)

  • Representation ➔ item present ⟺ bit is 1 ➔ the integer’s binary form is the set’s characteristic function.
  • Unbounded ➔ arbitrary-precision integers let it grow ➔ storage behind BVSet.
  • Set algebra ➔ bitwise logic: union |, intersection &, difference & ~ ➔ ideal for dense sets over a small universe.

2. Word-Parallelism & Popcount

  • Word-parallel ➔ one machine AND/OR combines 64 membership bits at once ➔ algebra over universe is words (), a ~ speedup.
  • Count = popcount ➔ naïve | Kernighan n &= n-1 | hardware POPCNT .
  • Universe-bound ➔ holding only still spans ~ bits ➔ cost tracks max value, not count.

⚙️ Core Implementation

🔹 Bitwise set operations

⚖️ Core Decision Matrix

OperationComplexityWhy
member / add / remove (per word)a few bitwise ops
union / intersection / differenceword-parallel & / | / & ~
count (__len__) POPCNT / Kernighanno count maintained
space bits1 bit/element — extremely compact for dense sets

When It Flips: right for dense small-integer sets with heavy membership/algebra (graph adjacency, dataflow analysis); wrong for sparse sets over a huge universe — use a hash set ( expected, space ∝ count) or a Bloom filter (probabilistic, sub-linear).

📊 Exam Execution Trace

Manual Execution Trace

add 1, add 3, add 4, then ∪ {2,3}:

Step / StateTrigger Opelems (binary)Set
0 (Init)init0000
1add 10001
2add 30101
3add 41101
401101111

Applied Exercise

Problem: Quantify the word-parallel union speedup. Derivation Proof / Hand-Calculation Walkthrough:

Final Extracted Output: ~ constant-factor gain — same order, dramatically smaller constant on dense universes.

🧠 Active Recall