Naive Solution:
import random
def gen_list():
bin_list=[]
count=(0,0)
while len(bin_list)<48:
choice=random.randint(0,1)
if choice==0:
bin_list.append(0)
count=(count[0]+1,count[1])
else:
bin_list.append(1)
count=(count[0],count[1]+1)
violates_run_constraint=(len(bin_list)>3) and (bin_list[-1]==bin_list[-2]==bin_list[-3])
if violates_run_constraint:
return ([],())
return (bin_list,count)
bin_list,count=gen_list()
while(bin_list==[] or count!=(24,24)):
bin_list,count=gen_list()
print(bin_list,count)
gen_list()
creates a list of length 48 that only contains 1s and 0s, selected randomly. It also keeps track of how many 1s and 0s it has used and returns this information as a tuple.
However, it can also fail, and violate the constraints. If it does this, it simply returns an empty list.
The outer loop generates lists until it gets a non-constraint-violating list and the number of 1s and the number of 0s in the generated list equals 24.
Probably not the most efficient solution, but definitely works, and a lot faster than I expected.
Example Outputs:
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] (24, 24)
[1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0] (24, 24)