是否有任何有效的代码可以生成二进制表示中带有n位数的数字,并且r位设置为1?
这也是生成掩码以找到集合的NcR组合的好策略吗?
我考虑过生成所有2 ^ n个数字并计算它们的位数,但是计数位似乎是O(nlogn)。
答案 0 :(得分:0)
好吧,如果我们给出一个设置了K位的数字,我们怎样才能找到设置了K位的次最大数字?如果我们反复这样做,我们可以生成所有这些。
生成下一个分解为几个简单的规则:
事实证明,很少有二进制数学技巧可以轻松实现所有这些规则。这是python:
N = 6 # length of numbers to generate
K = 4 # number of bits to be set
cur = (1<<K)-1 #smallest number witk K bits set
while cur < (1<<N):
print format(cur,'b')
#when you subtract 1, you turn off the lowest 1 bit
#and set lower bits to 1, so we can get the samallest 1 bit like this:
lowbit = cur&~(cur-1)
#when you add lowbit, you turn it off, along with all the adjacent 1s
#This is one more than the number we have to move into lower positions
ones = cur&~(cur+lowbit)
#cur+lowbit also turns on the first bit after those ones, which
#is the one we want to turn on, so the only thing left after that
#is turning on the ones at the lowest positions
cur = cur+lowbit+(ones/lowbit/2)
您可以在此处试用:https://ideone.com/ieWaUW
如果你想使用位掩码枚举NcR组合,那么这是一个很好的方法。如果您希望拥有所选项目的索引数组,那么最好使用不同的过程。你也可以像上面那样制定3个规则来增加那个数组。