Skip to content
BytePatterns

Bitmask as a Set

Bit Manipulation: lesson 5 of 5

An integer is a subset; counting to 2^n lists them all.

Lesson 5 of 5 · 5 min

Bitmask as a Set

Step 1 of 10

Give every item a lane: a is the 1, b the 2, c the 4. One integer now describes a whole subset.

The Idea

Give each item a lane. Then one integer describes a whole subset: lane i is 1 when item i is in.

Counting from 0 to 2^n - 1 therefore enumerates every subset, in order, with no recursion. Union is |, intersection is &, membership is mask >> i & 1.

Real-World Example

Travelling-salesman and scheduling solvers keep "which cities have I already visited?" as one 20-bit integer. It is the dictionary key for memoisation — comparing and hashing a set of 20 items collapses to comparing two machine words.

The Code

items = ["a", "b", "c"]

for mask in range(1 << len(items)):   # 0 .. 7
    picked = [items[i] for i in range(len(items)) if mask >> i & 1]
    print(mask, format(mask, "03b"), picked)

# 0 000 []
# 1 001 ['a']
# 2 010 ['b']
# 3 011 ['a', 'b']
# ...
# 7 111 ['a', 'b', 'c']

Python

Your turn

Fill in the blank.

items = ["a", "b", "c"]
mask = 5

picked = [items[i] for i in range(3) if ___]
print(picked)   # want ['a', 'c']

Mini quiz

1 / 3

How many subsets does a 20-element set have?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.