0

I need to simulate a poker-table-like queue where the users take their positions based on the first available seat. I've seen it done with lists, but I have solved it using bitwise ops.

def add_user_to_table(max_users=8):
    global tbl
    # simulate the first position: 00000001
    pos = 1
    # iterate through all positions. break once found empty position
    for i in range (0, max_users):
        if not (tbl & pos):
            # found an empty position...
            # return position, break, etc...
        else:
            # shift the bit 1 position left to check the next position
            # so after the 1st iteration pos will be 00000010
            pos = pos << 1

# main. Define a table with some users seated
# a table with seats 1, 3, 4, 6 taken
tbl = int('00101101', 2)
# now place the user on the first available seat (second seat in this example)
add_user_to_table()

In terms of performance (I will need thousands of tables with dozens of users), will this be the fastest and most efficient way?
Would lists/queues/deques etc. out-perform this method?

user1102018
  • 4,369
  • 6
  • 26
  • 33

2 Answers2

1

Your method will probably outperform lists/queues but there's only one way to find out. Simulate! Spawn processes/threads with 1000s of tables with different configs of users. I bet you would have to do this anyway before releasing your system.

Sid
  • 7,511
  • 2
  • 28
  • 41
0

If you're going to twiddle bits for efficiency you might as well go all the way and use one of the many cool bit twiddling hacks for doing this kind of thing - see Position of least significant bit that is set

In particular, the for loop you gave for finding the lowest clear bit in the table can be replaced with:

pos = ~tbl & ~(~tbl -1)

If you need to find the number of the bit instead of the actual bit, there are an assortment of cool hacks for doing that quickly as well.

Community
  • 1
  • 1
ikedim
  • 1