How to create 10 random x, y coordinates in a grid using Python

I need to create an 8x8 grid and distribute 10 coins in random positions on the grid. The problem I am facing is that the randint function sometimes generates the same random coordinates, and therefore only 9 or 8 coins are generated and put into the grid. How can I make sure this does not happen? Cheers :) This is my code:

from random import randint

grid = []
#Create a 8x8 grid
for row in range(8):
    grid.append([])
    for col in range(8):
        grid[row].append("0")

#create 10 random treasure chests
    #problem is that it might generate the same co-ordinates and therefore not enough coins
for coins in range(10):
    c_x = randint(0, len(grid)-1)
    c_y = randint(0, len(grid[0])-1)
    while c_x == 7 and c_y == 0:
           c_x = randint(0, len(grid)-1)
           c_y = randint(0, len(grid[0])-1)
    else:
        grid[c_x][c_y] = "C"

for row in grid:
print(" ".join(row))

I turned on while / else - since there should be no coin in the lower left corner of the grid

+4
source share
4 answers

So you want to generate 10 random unique coordinates?

You can use the kit to check:

cords_set = set()
while len(cords_set) < 10:
    x, y = 7, 0
    while (x, y) == (7, 0): 
        x, y = randint(0, len(grid) - 1), randint(0, len(grid[0]) - 1)
    # that will make sure we don't add (7, 0) to cords_set
    cords_set.add((x, y))

, (x, y).

print(cords_set):

{(5, 6), (7, 6), (4, 4), (6, 3), (7, 4), (6, 2), (3, 6), (0, 4), (1, 7), (5, 2)}

{(7, 3), (1, 3), (2, 6), (5, 5), (4, 6), (3, 0), (0, 7), (2, 0), (4, 1), (6, 5)}

{(1, 2), (1, 3), (6, 7), (3, 3), (4, 5), (4, 4), (6, 0), (1, 0), (2, 5), (2, 4)}
+5

64 , (x, y), random.sample, 10 , .

import random
from itertools import product

g = [['0' for _ in range(8)] for _ in range(8)]

coord = list(product(range(8), range(8)))
for coins in random.sample(coord, 10):
    g[ coins[0] ][ coins[1] ] = 'C'

for row in g:
    print(' '.join(row))
+5

while, , . BTW, , , randint , .

7 * 7 = 49 ( ), 10 np.random.choice.

+1

:

from random import randint

grid = []
#Create a 8x8 grid
for row in range(8):
    grid.append([])
    for col in range(8):
        grid[row].append("0")

for coins in range(10):
    c_x = randint(0, len(grid)-1)
    c_y = randint(0, len(grid[0])-1)
    while grid[c_x][c_y] == "C":
        c_x = randint(0, len(grid) - 1)
        c_y = randint(0, len(grid[0]) - 1)
    grid[c_x][c_y] = "C"

After creating the coordinates that you check to make sure that it does not have a “C” on it before assigning it to it. If you draw again and double-check. If this does not happen, you assign one and draw the next.

Let me know if this helps ☺

0
source

Source: https://habr.com/ru/post/1650886/


All Articles