如果我可以重申您的问题,我认为您正在寻找“如何从 m 个可用号码中随机挑选 n 个号码?”
换句话说,如果您有[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 作为可用号码并且您想选择4,那么一个可能的结果是[8, 3, 5, 1]。
有几种方法可以做到这一点。最简单的方法之一是将初始列表按随机顺序排列,然后取出顶部 n 个元素。
例如,在 Python 中:
>>> available = range(10)
>>> random.shuffle(available)
>>> available[:4]
[5, 8, 6, 9]
这个算法有点浪费,因为它会在你真的不需要的时候随机化整个列表。
一种改进是,一次一个元素,将该元素与它之后的随机位置交换。这被称为Fisher-Yates shuffle。在伪代码中看起来像这样:
-- To shuffle an array a of n elements (indices 0..n-1):
for i from 0 to n−2 do
j ← random integer such that i ≤ j < n
exchange a[i] and a[j]
但不是遍历整个列表,而是只深入 n,其中 n 是您需要选择的项目数。
这是一个 Python 实现:
import random
def sample(items, how_many):
# copy the list
items = list(items)
# just do the first how_many items
for i in range(how_many):
random_index = random.randrange(i, len(items))
# swap the items
items[i], items[random_index] = items[random_index], items[i]
# return the first how_many
return items[:how_many]
print(sample(range(10), 4))
许多语言/库都有执行此操作的内置方法。例如,在 Python 中,内置的 random.sample 相当于我上面的代码:
>>> random.sample(range(10), 4)
[1, 5, 0, 4]