:-use_module(library(clpfd)).


% N is the dot product of lists V1 and V2.
dot(V1, V2, N) :- maplist(product,V1,V2,P), sumlist(P,N).
product(N1,N2,N3) :- N3 is N1*N2.

% Matrix multiplication with matrices represented
% as lists of lists. M3 is the product of M1 and M2
mmult(M1, M2, M3) :- transpose(M2,MT), maplist(mm_helper(MT), M1, M3).
mm_helper(M2, I1, M3) :- maplist(dot(I1), M2, M3).


suml([],[],[]).

suml(L1,L2,[E1 + E2|R2]):-
    L1 = [E1|T1],
    L2 = [E2|T2],
    suml(T1,T2,R2).



summ([],[],[]).
summ(M1,M2,[Lr|R2]):-
    M1 = [E1|T1],
    M2 = [E2|T2],
    suml(E1,E2,Lr),
    summ(T1,T2,R2).


flatten(List, Flattened):-
  flatten(List, [], Flattened).

flatten([], Flattened, Flattened).
flatten([Item|Tail], L, Flattened):-
  flatten(Item, L1, Flattened),
  flatten(Tail, L, L1).
flatten(Item, Flattened, [Item|Flattened]):-
  \+ is_list(Item).

touspositifs(X):-
    flatten(X,XF),
    tp(XF).

tp([]).
tp(X):-
    X = [E|L],
    E #> 0,
    tp(L).






sc3(X):-
    mmult(X,X,X2),
    mmult(X,X2,X3),
    mmult(X,X3,X4),
    mmult(X,X4,X6),
    mmult(X,X4,X6),
    mmult(X,X6,X7),
    mmult(X,X7,X8),
    summ(X,X2,S1),
    summ(S1,X3,S2),
    summ(S2,X4,S3),
    summ(S3,X5,S4),
    summ(S4,X6,S5),
    summ(S5,X7,S6),
    summ(S6,X8,S7),
    touspositifs(S7).

sc2(X):-
    mmult(X,X,X2),
    mmult(X,X2,X3),
    mmult(X,X3,X4),
    summ(X,X2,S1),
    summ(S1,X3,S2),
    summ(S2,X4,S3),
    touspositifs(S3).





bistoc(X):-
    X=[[A,B,C,0],[F,E,0,G],[H,0,I,J],[0,K,L,M]],
    A in 0..2,
    E in 0..2,
    I in 0..2,
    M in 0..2,
    B in 0..1,
    C in 0..1,
    F in 0..1,
    G in 0..1,
    H in 0..1,
    J in 0..1,
    K in 0..1,
    L in 0..1,
    A + B + C  #= 2,
    E + F+  G #= 2,
    H+ I+ J#= 2,
    K+L +M #= 2,
    A+F + H#= 2,
    B+E +K #= 2,
    C+I + L#= 2,
    G+ J+M #= 2,
    label([A,B,C,F,E,G,H,I,J,K,L,M]),
    sc2(X).
    

display_m([]).
display_m([El|R]):-
    write(El),
    display_m(R).


solution(L):-
    get_time(T0),
    findall(X,bistoc(X),L),
    get_time(T1),
    DT is T1 - T0,
    write('but : '),writeln(DT),
    display_m(L).




