产生一个随机数与位置固定数目的最有效的方法 [英] Most efficient method of generating a random number with a fixed number of bits set

查看:214
本文介绍了产生一个随机数与位置固定数目的最有效的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要生成一个随机数,但它需要从该组二进制数与比特组人数相等选中。例如。随机选择一个字节值恰好有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

这篇关于产生一个随机数与位置固定数目的最有效的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆