:-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).




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(M):-
  M=[[M0_0, M0_1, 0, M0_3], [M1_0, M1_1, 0, M1_3], 
     [M2_0, 0, M2_2, M2_3], [0, M3_1, M3_2, M3_3]],
	 [M0_0, M1_1, M2_2, M3_3] ins 0..2,
  [M0_1, M0_3, M1_0, M1_3, M2_0, M2_3, M3_1, M3_2] ins 0..1,
  M0_0+ M0_1+ M0_2 #=2, M1_0+ M1_1+ M1_3 #=2,
  M2_0+ M2_2+ M2_3 #=2, M3_1+ M3_2+ M3_3 #=2,
  M0_0+ M1_0+ M2_0 #=2, M0_1+ M1_1+ M3_1 #=2, 
  M0_2+ M2_2+ M3_2 #=2, M1_3+ M2_3+ M3_3 #=2,
  mmult(M,M,M2),
  mmult(M,M2,M3),
  mmult(M,M3,M4),
  summ(M,M2,S2),
  summ(S2,M3,S3),
  summ(S3,M4,S4),
  allpositive(S4),
  label([M0_0, M0_1, M0_3, M1_0, M1_1, M1_3, M2_0, M2_2, M2_3, M3_1, M3_2, M3_3]),

  open('res2.txt',append,Stream), 
  write(Stream,M),  
  close(Stream).
    

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









