使用 CLPFD 生成不同值的列表
Generate a list of different values with CLPFD
我正在尝试生成三个元素列表的所有可能组合,其中所有元素都不同。我正在使用 CLPFD 库来定义变量的域。
我定义如下
listDif(F,X):-F ins 1..3,findall(F,all_distinct(F),X).
查询的答案是
?- listDif([1,_,2],X).
X = [[1, 3, 2]].
?- listDif([1,_,_],X).
X = [[1, _7374, _7380]],
_7374 in 2..3,
all_distinct([1, _7374, _7380]),
_7380 in 2..3.
?-
如何显示包含可能的整数值的列表?
如果您想使用 CLPFD 生成列表,则需要使用列表。 :) 您的代码仅使用单个整数。
list3(F) :-
length(F, 3), % F is a list of length 3
F ins 1..3, % Elements of F are in the range 1..3
all_distinct(F). % F has distinct elements
现在您有一个谓词,它对由 1、2、3 组成的唯一列表成功:
?- list3(F), label(F).
F = [1, 2, 3] ;
F = [1, 3, 2] ;
F = [2, 1, 3] ;
F = [2, 3, 1] ;
F = [3, 1, 2] ;
F = [3, 2, 1].
然后你可以使用findall/3
如果你想得到所有这些列表的列表:
?- findall(F, (list3(F), label(F)), AllList3).
AllList3 = [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]].
我正在尝试生成三个元素列表的所有可能组合,其中所有元素都不同。我正在使用 CLPFD 库来定义变量的域。
我定义如下
listDif(F,X):-F ins 1..3,findall(F,all_distinct(F),X).
查询的答案是
?- listDif([1,_,2],X).
X = [[1, 3, 2]].
?- listDif([1,_,_],X).
X = [[1, _7374, _7380]],
_7374 in 2..3,
all_distinct([1, _7374, _7380]),
_7380 in 2..3.
?-
如何显示包含可能的整数值的列表?
如果您想使用 CLPFD 生成列表,则需要使用列表。 :) 您的代码仅使用单个整数。
list3(F) :-
length(F, 3), % F is a list of length 3
F ins 1..3, % Elements of F are in the range 1..3
all_distinct(F). % F has distinct elements
现在您有一个谓词,它对由 1、2、3 组成的唯一列表成功:
?- list3(F), label(F).
F = [1, 2, 3] ;
F = [1, 3, 2] ;
F = [2, 1, 3] ;
F = [2, 3, 1] ;
F = [3, 1, 2] ;
F = [3, 2, 1].
然后你可以使用findall/3
如果你想得到所有这些列表的列表:
?- findall(F, (list3(F), label(F)), AllList3).
AllList3 = [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]].