 # Permutations with constraints

Hi all.

I have a set of numbers: {0,1,2,3}. I need to generate a list of permutations of this, but with constraints. Basically, the individual numbers in each permutation cannot exceed the relative value in the set.

For example, {0,1,1,2}, {0,0,2,3}, {0,1,0,1} would be legal, but {1,0,0,0}, {3,2,1,0}, {2,1,0,0} are illegal.

I have only managed to generate all possible permutations without those constraints in ghpython - unfortunately i have been unable to apply the constraints.

Does anyone know how I may accomplish this?

I this this is not permutation. Just use random.randint().

``````import random
res=[]
N=4
N2=3
for k in range(10):
aa=[]
prevval=0
for i in range(4):
nextval=random.randint(prevval,N2)
aa.append(nextval)
prevval=nextval
res.append(aa)
for aa in res:
print aa
``````

[3, 3, 3, 3]

[2, 3, 3, 3]

[1, 3, 3, 3]

[0, 0, 0, 1]

[0, 1, 3, 3]

[2, 2, 2, 2]

[0, 3, 3, 3]

Hello,

I would do it this way:

``````def main():
constraints = [0,1,2,3]
constrained_permutations = [[]]
for max_value in constraints:
new_permutations = []
for cp in constrained_permutations:
for value in range(max_value + 1):
new_permutations.append(cp+[value])
constrained_permutations = new_permutations
print(constrained_permutations)

if __name__ == '__main__':
main()
``````
1 Like

Have not yet tried this out as I do not need it anymore. But let me quickly try it once i get the time to. Thanks!