这是模拟“扑克桌”的最有效方法吗?座位排队?
我需要模拟一个类似扑克桌的队列,用户根据第一个可用座位来确定自己的位置。 我见过它是用列表完成的,但我已经使用按位运算解决了它。
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()
就性能而言(我需要数千个表和数十个用户),这将是最快且最有效的方法吗?
列表/队列/双端队列等会优于此方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的方法可能会优于列表/队列,但只有一种方法可以找到答案。模拟!生成具有数千个具有不同用户配置的表的进程/线程。
我敢打赌,在发布您的系统之前,您无论如何都必须这样做。
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.
如果你想通过调整位来提高效率,你不妨一路走下去,使用许多很酷的位调整技巧之一来完成这种事情 - 请参阅 设置的最低有效位的位置
特别是,您为查找表中最低清除位而给出的 for 循环可以被替换与:
pos = ~tbl & ~(~tbl -1)
如果您需要查找位号而不是实际位,也可以使用各种很酷的技巧来快速完成此操作。
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.