I have a list containing integers, I would like to create a copy of it such that duplicate elements are at least some distance apart. I am aware that it would be necessary to have "enough" different elements and a sufficiently "long" starting list but I would like to create that copy or return a message that it is not possible.
Here is a python "possible" implementation but sometimes this program creates an infinite loop.
import random out =  pbs = [1, 2, 3, 1, 2, 3, 5, 8] l = len(pbs) step = 3 while l > 0: pb = random.choice(pbs) if pb in out: lastindex = out[::-1].index(pb) if (len(out) - lastindex) < step: continue pbs.remove(pb) out.append(pb) l += -1 print(out)
Thank you for your help.