Search code examples
prologconstraintsclpfd

Prolog constraint


I have 3 Constraints for a List:

  1. list ins 1..9
  2. all_different(list)
  3. lists in the list --> I get some lists from the list. every list from the list has to fulfill the constraint to be gapless. for example:

    List1 = [1,3,2,4];
    List2=[3,2,1];
    List3= [5,7,6]
    WRONG: List4=[1,4,3]

1 Question: You have an idea to set constraint 3? I would sort the lists and check for: Element1=Element2+1?

After all i want to use labeling([ff],list)

2 Question: I get a solution with labeling if i set contraint 3 like my idea?


Solution

  • I think this is along the lines of what you're looking for...

    :- use_module(library(clpfd)).
    
    foo(L) :-
        Len in 1..9,    % lists of length 1 through 9
        length(L, Len),
        L ins 1..9,
        label(L),
        msort(L, LS),
        series(LS).
    
    series([_]).
    series([X,Y|T]) :- Y #= X + 1, series([Y|T]).
    

    Since you are already constraining the list to a specific series behavior, indicating all_different would be redundant.

    Another approach could be:

    foo(L) :-
        [Fst,Lst] ins 1..9,
        Fst #=< Lst,
        Len #= Lst - Fst + 1,
        length(L, Len),
        label([Fst,Lst]),
        L ins Fst..Lst,
        all_different(L),
        label(L).
    

    These predicates generate all possible lists meeting the criteria, and should succeed if and only if the given list meets the criteria.