Permutation Prolog

℡╲_俬逩灬. 提交于 2019-12-24 04:15:26

问题


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:


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.



来源:https://stackoverflow.com/questions/27350677/permutation-prolog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!