【问题标题】:How to generate random integer pairs between 0 and 31?如何生成 0 到 31 之间的随机整数对?
【发布时间】:2020-11-04 08:50:25
【问题描述】:

如题所示,我要生成100对随机整数,如(1, 0)、(1, 31)、(5, 7)、(3, 19)等。取值范围是0到31。同时,我希望每一对在100对中只出现一次,即每一对的值都不同。

那么如何在 Python 中实现呢?

补充:

准确地说,我想要的是一个二维数组,它的形状是(100,2)。每行都必须是唯一的。

【问题讨论】:

  • 请注意,您应该会开始看到大约 32 对的重复项。见en.wikipedia.org/wiki/Birthday_problem
  • 例如 ( 3, 2 ) 和 ( 2, 3 ) 的对算作不同的对吗?
  • @TlsChris 是的,它们是不同的

标签: python numpy random integer


【解决方案1】:

你可以使用random.sample:

import random

pool = range(32)
random.sample(pool, 2)
# [7, 28]
random.sample(pool, 2)
# [15, 3]

【讨论】:

  • 所以对于random.sample,我需要迭代32次
【解决方案2】:
import numpy as np

pool_ = [ (i,j) for i in range(32) for j in range(32) ]
# List of all pairs

pool = np.zeros( len(pool_), dtype = tuple ) # Create an np.array of tuples

pool[:] = pool_  # fill it with pool_

selected = np.random.choice( pool, replace = False, size =100 )
# select 100 random choices from the pool, without replacement

print( selected )
# [(0, 22) (4, 30) (2, 25) (4, 19) (6, 6) (17, 22) (18, 14) (12, 27) (30, 6)
# (22, 18) (13, 5) (23, 22) (27, 17) (17, 26) (26, 22) (7, 15) (15, 27)
# (4, 31) (15, 1) (28, 22) (25, 16) (25, 15) (7, 12) (7, 21) (26, 14)
# (9, 9) (8, 0) (26, 27) (14, 14) (22, 0) (4, 18) (12, 3) (25, 9) (22, 31)
# (11, 6) (23, 7) (18, 19) (19, 25) (23, 19) (25, 5) (5, 19) (3, 24)
# (30, 0) (18, 10) (20, 4) (24, 11) (13, 28) (10, 5) (6, 7) (11, 7)
# (25, 24) (23, 18) (15, 10) (14, 7) (11, 11) (9, 23) (13, 8) (3, 28)
# (28, 3) (21, 3) (24, 31) (29, 27) (24, 28) (17, 6) (30, 19) (25, 28)
# (12, 17) (13, 15) (3, 11) (14, 1) (12, 6) (17, 17) (23, 2) (24, 18)
# (25, 11) (3, 26) (6, 2) (0, 28) (5, 12) (4, 1) (23, 17) (29, 23) (22, 17)
# (24, 15) (2, 5) (28, 11) (19, 27) (9, 20) (1, 11) (30, 5) (30, 21)
# (30, 28) (18, 31) (5, 27) (30, 11) (16, 0) (24, 16) (12, 30) (25, 25)
# (16, 22)]

我尚未对其进行彻底测试,但在 random.choice 中使用 replace = False,每个选择都应该是唯一的。

返回二维数组

import numpy as np

pool_ = [ (i,j) for i in range(32) for j in range(32) ]
# List of all pairs

pool_ix = np.arange( len(pool_) ) # index by row

pool = np.array(pool_) # 2D pool

selected_ix = np.random.choice( pool_ix, replace = False, size =100 )

pool[selected_ix, : ]  # Select all of each selected row.

# array([[12, 19],
#        [ 6, 23],
#        [ 2,  3],
#        [ 5, 20],
#           :::
#        [20,  3],
#        [24, 20],
#        [ 1, 28]])

【讨论】:

    猜你喜欢
    • 2011-04-29
    • 1970-01-01
    • 2014-04-11
    • 2011-08-10
    • 2012-04-18
    • 1970-01-01
    • 2015-11-10
    • 1970-01-01
    • 2011-07-07
    相关资源
    最近更新 更多