slin
slin

Reputation: 411

Generating random coordinates with certain positions blocked

I have a two-dimensional array (18x24) and want to generate a random position in this array. However, certain positions should be blocked (These positions are stored as tuples in another list).

I could randomly generate the x and y coordinates and check wether the position is blocked and if so generate a new pair of coordinates. But this seems to be very inefficient especially with many positions blocked.

Upvotes: 1

Views: 162

Answers (1)

Adam.Er8
Adam.Er8

Reputation: 13393

You can generate an "allowed-list" (the complement of the blocked list) and choose a random option from there.

could be easily achieved with set difference.

import random

all_coordinates = {(x,y) for x in range(1,19) for y in range(1,25)}
blocked = {(11,19), (9,4), (2,2)} # just an example

allowed = all_coordinates - blocked

random_allowed = random.choice(list(allowed))
print(random_allowed)

Upvotes: 4

Related Questions