Search code examples
prologclpfd

Generate a list of different values with CLPFD


I am trying to generate all possible combinations of lists of three elements where all are distinct. I am using the CLPFD library to define the domain of the variable.

I defined the following

listDif(F,X):-F ins 1..3,findall(F,all_distinct(F),X).

And the answers to the queries are

?- 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.

?- 

How do I display the lists with the possible integer values?


Solution

  • If you want to generate lists with CLPFD then you need to use lists. :) Your code is just using individual integers.

    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
    

    Now you have a predicate which succeeds for unique lists consisting of 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].
    

    Then you can use findall/3 if you want to have a list of all of these lists:

    ?- 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]].