[英]Generating random values in a Python list that don't repeat in the same index
我正在编写一个程序,需要在其中生成随机值到列表中。 要求用户在2D网格上输入要生成多少个随机值(chts-用字母“ T”表示)。 问题在于,当用户键入“ 8”作为他们希望生成的随机“小块”的数量时,有时仅会向网格生成5或6个箱子(可能是因为随机整数在网格上重复出现而不会网格中唯一点的索引)。 箱子的数量永远无法准确地显示在网格上。 如何确保将所有随机值分配给2D网格上的唯一索引?
def chests():
global chest
chest = int(input("How many chests would you like in the game?"))
for i in range(0,chest):
board[randint(0, 4)][randint(0, 4)] = "T"
return board
在我看来,您需要生成所有可能的索引,然后随机选择一个“填充”:
import itertools
import random
chest_count = 8
BOARD_SIZE = 4
indices = list(itertools.product(range(BOARD_SIZE), repeat=2))
chest_locations = random.sample(indices, chest_count)
for i, j in chest_locations:
board[i][j] = 'T'
这最终是O(BOARD_SIZE^2)
。 还有更复杂的方法-例如,而不需要产生整个电路板的指数,你可以品尝扁平板的人口,然后生成后,该指数:
locations = random.sample(range(BOARD_SIZE * BOARD_SIZE), chest_count) # xrange on python2.x
for location in locations:
j, i = divmod(location, BOARD_SIZE)
board[i][j] = 'T'
最终结果是O(chest_count)
,它可能比电路板的尺寸小得多-但是,我怀疑您的电路板实际上足够大以至于很重要:-)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.