If you have 4 lists A, B, C, and D that contain objects of particular length, like list A
has n_a
elements and all the elements are of width 1, list B
has n_b
elements and all the elements are of width 2, list C
has n_c
elements and all the elements are of width 3, and list D
has n_d
elements and all the elements are of width 4. The first goal is to create an array whose elements are randomly sampled from A, B, C and D according to a user defined probability distribution like {1: 0.25, 2: 0.25, 3: 0.5, 4: 0.0}. For instance, with distribution={1: 0.5, 2:0.5} the output grid should yield random elements with roughly 25% 1-width elements from list A, 25% 2-width elements from list B and 50% 3-width elements from list C, while disallowing 4-width elements.
Here is how I am randomly sampling elements from all 4 lists:
import numpy as np
import random
A = [1, 2, 3]
B = ['aa', 'bb', 'cc']
C = [111, 222, 333]
D = ['aaaa', 'bbbbb', 'cccc']
num_of_rows = 4 # no. of rows in the final grid
num_of_coulmns = 5 # no. of columns in the final grid
# Define the probabilities
p_A = 0.25
p_B = 0.25
p_C = 0.5
p_D = 0.0
probabilities = [p_A, p_B, p_C, p_D]
# Create the random length array by sampling from the lists
result_array = []
for _ in range(num_of_rows):
# Choose a list based on the probabilities
chosen_list = random.choices([A, B, C, D], weights=probabilities, k=1)[0]
# Sample a random element from the chosen list
element = random.choice(chosen_list)
# Append the element to the result array
result_array.append(element)
But this method will be too inefficient for larger values of rows and columns of grid (like 1000). Is there a better way to achieve this.