给定长度的列表与Prolog中排列的组合? [英] A combination of a list given a length followed by a permutation in Prolog?

查看:188
本文介绍了给定长度的列表与Prolog中排列的组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个谓词来返回包含输入列表的所有组合的列表,并且列表结果的大小在第二个参数中,谓词就是这样

I need a predicate to return a list with all combinations of the input list, and the list result size is in the second param, the predicate would be like this

permutInListN( +inputList, +lengthListResult, -ListResult), 

示例:

permutInListN([1,2,3],2,L).
? L=[1,2].
? L=[2,1].
? L=[1,3].
? L=[3,1].
? L=[2,3].
? L=[3,2].

列表L中长度为2[1,2,3]的组合. 没有重复可能使用抵消.

Combinations of [1,2,3] in a list L with length 2. with no repetitions maybe using setoff.

这是我的代码,但是根本不起作用,没有生成所有解决方案

this is my code but it doesn't work at all , no generate all solutions

permutInListN(_, 0, []).
permutInListN([X|Xs], N, [X|Ys]) :- N1 is N-1, permutInListN(Xs,N1,Ys).
permutInListN([_|Xs], N, Y) :- N>0, permutInListN(Xs,N,Y).

?permutInListN([1,2,3],2,L).
L = [1, 2]
L = [1, 3]
L = [2, 3]

提前谢谢.

推荐答案

您想要的是组合后跟排列的组合.

What you want is a combination followed by a permutation.

对于组合:

comb(0,_,[]).

comb(N,[X|T],[X|Comb]) :-
    N>0,
    N1 is N-1,
    comb(N1,T,Comb).

comb(N,[_|T],Comb) :-
    N>0,
    comb(N,T,Comb).

示例:

?- comb(2,[1,2,3],List).
List = [1, 2] ;
List = [1, 3] ;
List = [2, 3] ;
false.

对于置换,只需在库列表中使用SWI-Prolog permutation/2

For Permutation just use SWI-Prolog permutation/2 in library lists

:- use_module(library(lists)).

?- permutation([1,2],R).
R = [1, 2] ;
R = [2, 1] ;
false.

将它们放在一起

comb_perm(N,List,Result) :-
    comb(N,List,Comb),
    permutation(Comb,Result).

与您的查询

?- comb_perm(2,[1,2,3],R).
R = [1, 2] ;
R = [2, 1] ;
R = [1, 3] ;
R = [3, 1] ;
R = [2, 3] ;
R = [3, 2] ;
false.

为您的谓词修改

permutInListN(List,N,Result) :-
    comb(N,List,Comb),
    permutation(Comb,Result).

示例

?- permutInListN([1,2,3],2,R).
R = [1, 2] ;
R = [2, 1] ;
R = [1, 3] ;
R = [3, 1] ;
R = [2, 3] ;
R = [3, 2] ;
false.

这篇关于给定长度的列表与Prolog中排列的组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆