Bitwise enumeration is a technique that explores all possible selections using bit operations (0,1). This approach is useful for:
- Enumerating all subsets of a set with
N
elements. - Exploring all possible choices when there are
N
binary decisions (e.g., “YES” or “NO”).
These scenarios are essentially the same. For example, enumerating all subsets of a set with N
elements is equivalent to determining all possible ways to either “select” or “not select” each element.
Concept of Bitwise Enumeration #
A binary decision (two choices) can be represented using binary digits (0 or 1). For example, assume three animals: dog, cat, and bird. If selecting an animal is xrepresented as 1
and not selecting as 0
, then different combinations can be represented in binary:
Dog | Cat | Bird | Binary Representation | Decimal Representation |
---|---|---|---|---|
× | × | × | 000 | 0 |
× | × | ◯ | 001 | 1 |
× | ◯ | × | 010 | 2 |
× | ◯ | ◯ | 011 | 3 |
◯ | × | × | 100 | 4 |
◯ | × | ◯ | 101 | 5 |
◯ | ◯ | × | 110 | 6 |
◯ | ◯ | ◯ | 111 | 7 |
Each pattern represents a unique subset selection, which can be efficiently generated using a simple algorithm.
When to Use Bitwise Enumeration #
Bitwise enumeration is effective when exploring all patterns involving N
binary choices. Although alternative implementations exist, bitwise enumeration offers a concise and intuitive approach. However, since the computational complexity is \(N * 2^N\), this method becomes impractical for large values of N
.
Implementation of Bitwise Enumeration #
The following Python implementation generates all subsets of a given list:
sample_list = ['A', 'B', 'C', 'D']
# Count elements
len_sample_list = len(sample_list)
# Explore all selection patterns using 2^N iterations
for i in range(2 ** len_sample_list):
out_list = []
# Check each bit position
for j in range(len_sample_list):
# Use bitwise AND to determine selected elements
if (i >> j) & 1:
out_list.append(sample_list[j])
print(out_list)
Since the input list contains four elements, \(2^4 = 16\) different subsets are generated.