简体   繁体   English

检查随机生成的列表中的重复项并替换它们

[英]Check for duplicates in a randomly generated list and replace them

I am making a minesweeper game with randomly generated bombs. 我正在用随机生成的炸弹进行扫雷游戏。 Yet at times I have found that there are duplicates in my list of coordinates of bombs. 但有时我发现炸弹坐标列表中有重复。 How do I check for duplicates in a list and replace them with other randomised coordinates. 如何检查列表中的重复项并将其替换为其他随机坐标。

from random import randint

def create_bombpos():
    global BOMBS, NUM_BOMBS, GRID_TILES
    for i in range(0, NUM_BOMBS):
        x = randint(1, GRID_TILES)
        y = randint(1, GRID_TILES)
        BOMBS.append((x, y))
    print(BOMBS)

The user can decide how big the board is by input of GRID_TILES . 用户可以通过输入GRID_TILES来决定电路板的GRID_TILES If they input 5, the board will be 5x5. 如果输入5,则电路板将为5x5。 The ammount of bombs is: 炸弹的数量是:

GRID_TILES * GRIDTILES / 5

Searching each time through your whole BOMBS list would cost you O(n) (linear time). 每次搜索整个BOMBS列表都会花费O(n) (线性时间)。 Why don't you use a set instead? 为什么不使用套装呢? a Set guarantees that you ll end up with distinct (in terms of hashing) elements. Set保证您最终会得到不同的(就散列而言)元素。

from random import randint

def create_bombpos():
BOMBS = set()
i = 0
while i<NUM_BOMBS:
   x = randint(1, GRID_TILES)
   y = randint(1, GRID_TILES)
   if (x,y) not in BOMBS
       BOMBS.add((x, y))
       i = i + 1
print(BOMBS)

Let me give u an example of a set: 让我举一个例子:

>>> a = set()
>>> a.add((1,2))
>>> a
{(1, 2)}
>>> a.add((1,2))
>>> a.add((1,3))
>>> a.add((1,2))
>>> a
{(1, 2), (1, 3)}

I can add the same element to a set many times, but only 1 instance will be present. 我可以多次向组中添加相同的元素,但只有1个实例存在。

from random import randint

def create_bombpos():
    global BOMBS, NUM_BOMBS, GRID_TILES
    i = 0
    while i<NUM_BOMBS:
       x = randint(1, GRID_TILES)
       y = randint(1, GRID_TILES)
       if (x,y) not in BOMBS
           BOMBS.append((x, y))
           i = i + 1
    print(BOMBS)

If the newly generated point is already in the list, then i won't get incremented, and we will find another newly generated point, till it is not present in BOMBS . 如果新生成的点已经在列表中,那么i将不会增加,我们将找到另一个新生成的点,直到它不存在于BOMBS

Hope it helps!! 希望能帮助到你!!

You could also use random.sample to achieve this: 您还可以使用random.sample来实现此目的:

from random import sample

GRID_TILES = 100
NUM_BOMBS = 5

indexes = sample(range(GRID_TILES * GRID_TILES), NUM_BOMBS)
BOMBS = [(i // GRID_TILES, i % GRID_TILES) for i in indexes]

Use a python set for this, it will automatically check for duplicates and simply ignore every entry that already is in the list. 为此使用python集,它将自动检查重复项并简单地忽略列表中已有的每个条目。 I also think the runtime is much better than using a list and checking for duplicates manually. 我还认为运行时比使用列表并手动检查重复项要好得多。

Link: https://docs.python.org/2/library/sets.html 链接: https//docs.python.org/2/library/sets.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM