mljistcart
mljistcart

Reputation: 45

Prolog constraint logic programming - Check if elements of list are different (list of lists)

I'm stuck on this exercise for some time. What I am trying to accomplish is:

Given a List of Lists, check if all elements are different. For example:

Ex1 -

L=[[1,2,3],[3,2,1],[2,1,3]], check_diff(L).
%must return true

Ex2 -

L=[[1,2,3],[2,3,1],[2,1,3]], check_diff(L).
%must return true

Ex3 -

L=[[1,2,3],[1,2,3],[3,1,2]], check_diff(L).
%must return false

My goal is, after knowing a solution to this, apply it to Prolog constraint logic programming in order to restrict the possibility of the elements of any list L (list of lists) being the same.

In other words: Apply all_different predicate on Sicstus Prolog but this time, for List of Lists.

Upvotes: 2

Views: 610

Answers (1)

damianodamiano
damianodamiano

Reputation: 2662

Here the solution using boolean variables (i wrote it using ECLiPSe prolog, sholud't be difficult translate it in another prolog...)

:-lib(fd).

allListsDifferent2([],[],[]).
allListsDifferent2([H1|T1],[H2|T2],[HB|TB]):-
    H1 #= H2 #<=> HB,
    allListsDifferent2(T1,T2,TB).

allListsDifferent1(_,[]).
allListsDifferent1(HA,[HB|T]):-
    length(HA,N),
    length(LB,N),
    LB::0..1,
    fd_global:sumlist(LB,S),
    S #< N,
    allListsDifferent2(HA,HB,LB),
    allListsDifferent1(HA,T).

allListsDifferent([_]).
allListsDifferent([HA,HB|T]):-
    allListsDifferent1(HA,[HB|T]),
    allListsDifferent([HB|T]).

?- allListsDifferent([[1, 2, 3], [3, 2, 1], [2, 1, 3]]).
Yes (0.02s cpu, solution 1, maybe more)
No (0.03s cpu)
?- allListsDifferent([[1, 2, 3], [3, 2, 1], [3, 2, 1]]).
No (0.00s cpu)

Upvotes: 2

Related Questions