% carre_latin_N.pl

carre_latin1(L,N) :-
     length(L, N),
     constraint_lg(L,N),
     constraint_col(L),
     flatten(L,Ls),
     fd_labelingff(Ls),
     ecriture(L).  

constraint_lg([],_).
constraint_lg([L|Ls],N):-
    length(L, N),
    fd_domain(L, 1, N),   
    fd_all_different(L),
    constraint_lg(Ls,N).


constraint_col(L):-
	collect_col(L,R,C),
	fd_all_different(C),
	constraint_col(R).	
constraint_col([[]|_]).	
collect_col([[E1|R1]|Ls],[R1|Rs],[E1|Es]):-
    collect_col(Ls,Rs,Es).
collect_col([[E1|R1]],[R1],[E1]).
  
ecriture([L1|L]):-
	 write(L1),nl,  ecriture(L).
ecriture([]).

% Sans flatten 

carre_latin2(L,N) :-
     length(L, N),
     constraint_lg(L,N),
     constraint_col(L),
     my_labeling(L),
     ecriture(L).  


my_labeling([]).
my_labeling([L|Ls]) :-
  fd_labelingff(L),
  labeling(Ls).


/*
| ?- carre_latin1(L,8), cpu_time(T). 
[1,2,3,4,5,6,7,8]
[2,8,1,3,4,5,6,7]
[3,1,8,7,2,4,5,6]
[4,3,5,6,8,7,1,2]
[5,4,7,2,6,3,8,1]
[6,5,2,1,7,8,3,4]
[7,6,4,8,3,1,2,5]
[8,7,6,5,1,2,4,3]

L = [[1,2,3,4,5,6,7,8],[2,8,1,3,4,5,6,7],[3,1,8,7,2,4,5,6],[4,3,5,6,8,7,1,2],[5,4,7,2,6,3,8,1],[6,5,2,1,7,8,3,4],[7,6,4,8,3,1,2,5],[8,7,6,5,1,2,4,3]]
T = 1 ? 

(1 ms) yes
*/

test1(L,T):-
L = [[1,2,3,4,5,6,7,8],[2,8,1,3,X,5,6,7],[3,1,8,7,2,4,5,6],[4,3,5,U,8,7,1,2],[5,V,W,2,6,3,8,1],[6,5,2,1,7,8,3,4],[7,Z,4,8,3,1,2,5],[8,7,Y,5,1,2,4,3]],
	cpu_time(T1),
	carre_latin1(L,8), 
	cpu_time(T2),
	T is T2-T1.


test2(L,T):-
L = [[1,2,3,4,5,6,7,8],[2,8,1,3,X,5,4,7],[3,1,8,7,2,4,5,6],[Z,3,R,U,8,7,1,2],[5,V,W,2,6,3,8,1],[6,5,2,1,7,8,3,4],[7,Z,4,8,3,1,2,5],[8,7,Y,5,1,2,4,3]],
	cpu_time(T1),
	carre_latin1(L,8),
	cpu_time(T2),
	T is T2-T1.




