state_index = 0 # 0 = DISCONNECTED, 1 = CONNECTED def handle_event(event): if state_index == 0 and event == "CONNECT": state_index = 1 # transition to CONNECTED print("Connected") elif state_index == 1 and event == "DISCONNECT": state_index = 0 print("Disconnected")
Always verify that your domain truly has exactly two mutually exclusive, exhaustive states. Pitfall 3: Forgetting About NULLs In SQL, a boolean column can be TRUE, FALSE, or NULL. NULL is a third state! If you create an index on two states but allow NULLs, your index is incomplete.
def count_ones(self): """Population count (number of indices in state 1)""" return bin(self.bitmap).count("1") index of 2 states
A B-tree index on a boolean column divides the data into exactly two branches. While functional, it doesn't leverage bitwise parallelism. A bitmap index is often 10x to 100x smaller and faster for read-heavy analytical queries.
print("Present students:", attendance.find_all_with_state(1)) print("Total present:", attendance.count_ones()) state_index = 0 # 0 = DISCONNECTED, 1
Using an integer index for two states is memory-efficient and prevents invalid states. In 2D game engines, every object on screen has an "active" or "inactive" state. The index of 2 states is used to maintain a sparse set of active objects. Instead of iterating over all 10,000 objects every frame, the engine maintains an array of indices where is_alive = 1 .
Consider a sparse binary matrix representing user permissions: If you create an index on two states
let allObjects = [objA, objB, objC, ...]; // 10,000 items let aliveIndices = [0, 2, 5, 7, ...]; // only 100 alive // Update only alive objects for (let i of aliveIndices) allObjects[i].update();