产生一个随机数与位置固定数目的最有效的方法目的、随机数、最有效、位置

2023-09-11 22:54:29 作者:秀恩愛 死得快

我需要生成一个随机数,但它需要从该组二进制数与比特组人数相等选中。例如。随机选择一个字节值恰好有2位设置......

I need to generate a random number, but it needs to be selected from the set of binary numbers with equal numbers of set bits. E.g. choose a random byte value with exactly 2 bits set...

00000000 - no
00000001 - no
00000010 - no
00000011 - YES
00000100 - no
00000101 - YES
00000110 - YES
...

=> Set of possible numbers 3, 5, 6...

请注意,这是一个简化的一组数字。多想想沿着'选择恰好有40位设置一个随机的64位数字的线路。从组中的每个数字必须是同样有可能出现的。

Note that this is a simplified set of numbers. Think more along the lines of 'Choose a random 64-bit number with exactly 40 bits set'. Each number from the set must be equally likely to arise.

推荐答案

做一个随机选择从集中的所有位位置,然后将这些位。

Do a random selection from the set of all bit positions, then set those bits.

例在Python:

def random_bits(word_size, bit_count):
    number = 0
    for bit in random.sample(range(word_size), bit_count):
        number |= 1 << bit
    return number

运行10次以上的结果:

Results of running the above 10 times:

0xb1f69da5cb867efbL
0xfceff3c3e16ea92dL
0xecaea89655befe77L
0xbf7d57a9b62f338bL
0x8cd1fee76f2c69f7L
0x8563bfc6d9df32dfL
0xdf0cdaebf0177e5fL
0xf7ab75fe3e2d11c7L
0x97f9f1cbb1f9e2f8L
0x7f7f075de5b73362L