Python Forum

Full Version: Preventing Duplicate Placement in 2D Array
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello all,

I'm writing a code to simulate respiratory virus propagation in a population. The code is massive, so attached is a small tidbit of it. The purpose of this section is to randomly assign each "human" to a randomly generated row and column without overlapping. The two main arrays are "Field" and "Directory". The Field array is simply for visuals. It displays the value of 1 where a human is supposed to be and a 0 in the empty space. The code has too much of a reliance on the Field array and I'd like to see it solely dependent on the Directory for its functionality.

Does anyone have any ideas on how I can get the code to randomly assign elements to a random row and column without overlap and without the need for the Field array?

Thanks!

from numpy import zeros, sum
from random import randint

N = 25 # number of people
A = 10 # length of field
B = 10 # width of field
D = 3 # columns for directory
field = zeros([A,B],int)
directory = zeros((N,D),float)

for i in range(N):
    open = 0
    while open == 0:
        row = randint(0,A-1)
        col = randint(0,B-1)
        if field[row,col] == 0:
            field[row,col] = 1
            directory[i,0] = i
            directory[i,1] = row
            directory[i,2] = col
            open = 1

print(sum(field)) # to check if the code works
Create a list of tuples for all possible combinations of row and col. Shuffle the list or randomly remove combinations from the list. This example shuffles the fields list and pops the combinations off the end.
from numpy import zeros, sum
import random
import itertools

N = 25 # number of people
A = 10 # length of field
B = 10 # width of field
D = 3 # columns for directory
directory = zeros((N,D),float)
# Create an entry for each row/column combination
fields = list(itertools.product(range(A), range(B)))
random.shuffle(fields)

for i in range(N):
    directory[i,0] = i
    directory[i,1], directory[i,2] = fields.pop()

print(directory)
[quote="deanhystad" pid='152955' dateline='1643928996']
Create a list of tuples for all possible combinations of row and col. Shuffle the list or randomly remove combinations from the list. This example shuffles the fields list and pops the combinations off the end.

Thanks Dean, this is actually incredibly helpful and the itertools module is definitely going to help in the rest of the code.