I have a list of 4 items, and I would like to find all possible combinations of these 4 items for a given array length. Ex: if I specify that I want the length to be 16, I want to generate all possible combinations of 16 items using the elements from the original list.
I also have restrictions, so I want each element in the original list to appear a certain number of times in the generated combinations.
Ex: colors = np.array(["red","blue", "green", "neon green"])
I want to generate all possible 16 element arrays that use these given colors in a certain ratio: "red" must appear 4 times, "blue" must appear 4 times, and "green" + "neon green" together must appear 8 times (it doesn't matter if we have 8 greens, 0 neon greens, or vice versa, or a mix of both as long as the sum of both in the combination is 8.
I tried using itertools.product to generate all possible combinations and then looping through each combination to see if it meets my criteria for a "valid array," but for a 16-element long combination, it times out (although this method does work if I want to do 4 or 8-element long combinations).
This is my current code:
def validCombinations(rows, columns):
possibleCombinations = product(colors,repeat=rows) #generates all the possible combinations
possibleCombos = [] #possible combinations that match our 1:2:1 ratio restriction
counter = 1
#loops through each combination and puts each ion in that combination into an array (array a)
for c in product(possibleCombinations,repeat=columns):
a = []
for i in c:
for j in i:
a.append(j)
#if a (the combination) contains a 1:2:1 ratio, then add it to the array of possible combos
if a.count("red") == (rows *columns)/4 and a.count("blue") == (rows *columns)/4 and (a.count("green") + a.count("neon green")) == (rows*columns)/2:
possibleCombos.append(a)
print(len(possibleCombos))
return(possibleCombos)
validCombinations(2,2) #for a list of 4 elements
#validCombinations(4,4) #for a list of 16 elements
#validCombinations(2,4) etc..
Is itertools.product() the right approach, or is there a faster alternative?