Permutation Prolog

2019-07-21 10:58发布

I am trying to make a list*list of all permutations from 1 to N

Example: perm(3, X). -> X = [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

I am instead getting

X = [1, 2, 3]

X = [1, 3, 2]

X = [2, 1, 3]

X = [2, 3, 1]

X = [3, 1, 2]

X = [3, 2, 1]

and having to keep hitting next. My question is how would I put all values of X into a list like the example run that I want. Here is my existing code:

permHelp([],[]).
permHelp(List,[H|Finish]):-delete(H,List,Rest),permHelp(Rest,Finish).

delete(X,[X|T],T).
delete(X,[H|T],[H|NT]):-delete(X,T,NT).

createList(0, L, L) :- !.
createList(N, R, L) :- N > 0, N1 is N-1, createList(N1, [N|R], L).

perm(N, X):- createList(N, [], L), permHelp(L, X).

1条回答
祖国的老花朵
2楼-- · 2019-07-21 11:08
perm(N, X):-
   createList(N, [], L),
   list_allperms(L, X).

With list_allperms/2 defined in another answer.

What you call permHelp should rather be called permutation.

查看更多
登录 后发表回答