PERMUTATIONS - back to content

		?- permutations([1,2],R).
 		R = [[1,2],[2,1]]
		?- add(a,[b,c,d],X).
		X = [a,b,c,d]
		X = [b,a,c,d]
		X = [b,c,a,d]
		X = [b,c,d,a]
		?- permut([a,b,c],X).
		X = [a,b,c]
		X = [b,a,c]
		X = [b,c,a]
		X = [a,c,b]
		X = [c,a,b]
		X = [c,b,a]

The number of permutations of a list with n elements is n! Algorithm: We take each element by turn and add it in front of each element. add(X,L,[X|L]). add(X,[L|H],[L|R]):- add(X,H,R). permut([],[]). permut([L|H],R):- permut(H,R1),add(L,R1,R). permutations(L,R):- findall(P,permut(L,P),R).