I need to loop through all possible combinations of an array for a project I'm doing. I'm doing this by looping through all integers in binary from 0 to 2^length of array - 1. Then, a 0 represents to not include the item at that index, and 1 represents to include the item at that index. Here is my code:
def binary_combinations(array):
combinations = []
total_combinations = 2 ** len(array) - 1
for i in range(total_combinations + 1):
binary_indexes = ("{:0" + str(len(array)) + "d}").format(int(str(bin(i))[2:]))
current_combination = []
for j in range(len(binary_indexes)):
if binary_indexes[j] == "1":
current_combination.append(array[j])
combinations.append(current_combination)
return combinations
So if I called print(binary_combinations([1, 2, 3, 4]), the output would be [[], [4], [3], [3, 4], [2], [2, 4], [2, 3], [2, 3, 4], [1], [1, 4], [1, 3], [1, 3, 4], [1, 2], [1, 2, 4], [1, 2, 3], [1, 2, 3, 4]].
In the context of my project, I want to check each combination as it is generated, instead of waiting for the entire array to be finished generating (so check the array [], if it works, break, otherwise move on to [4].
I am looking for the smallest possible array that satisfies a condition, so I need to loop through the sub-arrays from least to greatest length, and I don't have enough time to wait for the entire array of combinations to generate and then loop through it.
Is there a way to optimize the order of combinations I am creating, so the combinations are created in order of least to longest length?