Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to create a 8x8 grid and distribute 10 coins in random positions on the grid. The problem I am facing is that the randint function will sometimes generate the same random co-ordinates and therefore only 9 or 8 coins are generated and placed on the grid. How can I make sure this doesn't happen? Cheers :) This is my code so far:

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 have included a while/else - as there must not be a coin in the bottom left corner of the grid

like image 746
Miss SJ Avatar asked Dec 18 '22 14:12

Miss SJ


2 Answers

You only have 64 cases, so you can generate all coordinates as tuples (x,y) and then you can use random.sample to directly have 10 unique elements, so you don't have to check or redraw.

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))
like image 132
polku Avatar answered Dec 21 '22 03:12

polku


So you wish to generate 10 random unique coordinates?

You can use a set to verify:

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))

This will generate a set of tuples that represent (x, y) coordinates.

A few examples of the output of 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)}
like image 24
DeepSpace Avatar answered Dec 21 '22 03:12

DeepSpace