list - prolog中的list中生成K个元素的组合时如何忽略结果的第一个匹配?

在prolog中的list中生成K个元素的组合时,如何忽略结果的第一个匹配?

%这里是代码。

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

?- combination(3,[3,8,9,10,12,14],S).

%result will be.
S = [3, 8, 9] ;
S = [3, 8, 10] ;
S = [3, 8, 12] ;
S = [3, 8, 14] ;
S = [3, 9, 10] ;
S = [3, 9, 12] ;
S = [3, 9, 14] ;
S = [3, 10, 12] ;
S = [3, 10, 14] ;
S = [3, 12, 14] ;
S = [8, 9, 10] ;
S = [8, 9, 12] ;
S = [8, 9, 14] ;
S = [8, 10, 12] ;
S = [8, 10, 14] ;
S = [8, 12, 14] ;
S = [9, 10, 12] ;
S = [9, 10, 14] ;
S = [9, 12, 14] ;
S = [10, 12, 14] ;
false.


%I want to ignore the first match [3,8,9].

回答1

根据您想要的原因,有多种选择。

?- combination(3,[3,8,9,10,12,14],S).  % original question
   S = [3,8,9],     unexpected
;  S = [3,8,10]
;  S = [3,8,12]
;  ... .
?- dif(S,[3,8,9]), combination(3,[3,8,9,10,12,14],S).
   S = [3,8,10]
;  S = [3,8,12]
;  S = [3,8,14]
;  ... .
?- combination(3,[8,9,10,12,14],S).
   S = [8,9,10]
;  S = [8,9,12]
;  S = [8,9,14]
;  ... .
?- call_nth(combination(3,[3,8,9,10,12,14],S), Nth), Nth>1.
   S = [3,8,10], Nth = 2
;  S = [3,8,12], Nth = 3
;  S = [3,8,14], Nth = 4
;  ... .

首先,您可能不想要那个特定的解决方案,然后使用 dif/2,或者只使用较小的 list,最后,您想要排除第一个答案(在这种情况下也是第一个解决方案),然后使用http://www.complang.tuwien.ac.at/ulrich/iso-prolog/call_nth

相似文章

随机推荐

最新文章