I am developing a program in PROLOG (with restrictions) which is supposed to output a combination of 6 numbers within certain restrictions.
The list must have the numbers from 1 to 4 and will, consequently, repeat 2 other numbers. It is not possible not to have a number from 1 to 4.
Possible examples: Wrong examples:
1,2,3,4,1,1 1,2,3,2,3,3 //Missing #4
1,3,2,1,4,4 4,3,2,4,2,3 //Missing #1
1,2,3,3,2,4
4,1,3,2,1,4
In order to get this done I created some restrictions like the following:
Numbers = [A1, A2, A3, A4, A5, A6]
nCr(6,4) = 15 restrictions
A1 =\= A2 =\= A3 =\= A4 OR
A1 =\= A2 =\= A3 =\= A5 OR
Etc.
Here's the code I've developed so far:
make
pred(Numbers) :-
Numbers = [A1, A2, A3, A4, A5, A6],
domain(Numbers, 1, 4),
%restrictions
all_different([A1,A2,A6,A3]) #\/ %A1 =/= A2 =/= A6 =/= A3
all_different([A1,A2,A6,A4]) #\/ %A1 =/= A2 =/= A6 =/= A4
all_different([A1,A2,A6,A5]) #\/ %A1 =/= A2 =/= A6 =/= A5
all_different([A1,A2,A3,A4]) #\/ %A1 =/= A2 =/= A3 =/= A4
all_different([A1,A2,A3,A5]) #\/ %A1 =/= A2 =/= A3 =/= A5
all_different([A1,A2,A4,A5]) #\/ %A1 =/= A2 =/= A4 =/= A5
all_different([A1,A6,A3,A4]) #\/ %A1 =/= A6 =/= A3 =/= A4
all_different([A1,A6,A3,A5]) #\/ %A1 =/= A6 =/= A3 =/= A5
all_different([A1,A6,A4,A5]) #\/ %A1 =/= A6 =/= A4 =/= A5
all_different([A1,A3,A5,A4]) #\/ %A1 =/= A3 =/= A4 =/= A5
all_different([A2,A6,A3,A4]) #\/ %A2 =/= A6 =/= A3 =/= A4
all_different([A2,A6,A3,A5]) #\/ %A2 =/= A6 =/= A3 =/= A5
all_different([A2,A6,A4,A5]) #\/ %A2 =/= A6 =/= A4 =/= A5
all_different([A2,A3,A4,A5]) #\/ %A2 =/= A3 =/= A4 =/= A5
all_different([A6,A3,A4,A5]), %A6 =/= A3 =/= A4 =/= A5
labeling([], Numbers).
The logic seems fine to me, but this implementation is not working as it should. There are no solutions which meet the restrictions typed. Can anyone give me a hand?
| ?- pred([A1, A2, A3, A4, A5, A6]).
no
this query should satisfy your requirements
?- Vs = [_,_,_,_,_,_], Vs ins 1..4,
[A,B,C,D] ins 1..2, global_cardinality(Vs, [1-A,2-B,3-C,4-D]), label(Vs).
Vs = [1, 1, 2, 2, 3, 4],
A = B, B = 2,
C = D, D = 1 ;
Vs = [1, 1, 2, 2, 4, 3],
A = B, B = 2,
C = D, D = 1 ;
...
Here are two alternative queries using clpfd constraints:
Using the nvalue/2
constraint, available with SICStus Prolog:
?- Vs = [_,_,_,_,_,_], domain(Vs,1,4),
nvalue(4,Vs),
labeling([],Vs).
Using the element/3
constraint, the clpfd sibling of nth1/3
and member/2
:
?- Vs = [_,_,_,_,_,_], domain(Vs,1,4),
element(_,Vs,1),element(_,Vs,2),element(_,Vs,3),element(_,Vs,4),
labeling([],Vs).
Both queries give the same solution sequence:
Vs = [1,1,1,2,3,4] ? ;
Vs = [1,1,1,2,4,3] ? ;
Vs = [1,1,1,3,2,4] ? ;
Vs = [1,1,1,3,4,2] ? ;
Vs = [1,1,1,4,2,3] ? ;
Vs = [1,1,1,4,3,2] ? ...
The list above only includes the first few results, there are 1560 in total.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With