%LP 2011-2012  DCC-FCUP
:-dynamic(tenta/2).

mmind(C):- limpa, tentativa(C), verifica(C), anuncio.

tentativa(C):-
    C=[X1,X2,X3,X4], selects(C,[1,2,3,4,5,6,7,8,9,0]).

verifica(C):- not inconsistente(C), pergunta(C).

pergunta(C):- repeat,
	     writeln(['Quantos brancos e quantos pretos em',C,'?']),
	     read((B,P)),
	     coerente(B,P), !,
	     assert(tenta(C,B,P)), 
	     B=4.
		
coerente(B,P):- integer(B), integer(P), B+P =< 4.

inconsistente(C):-
     tenta(C1,B,P),
     not b_e_p(C1,C,B,P).
			 
b_e_p(C1,C,B,P):-
   exactos(C1,C,B1),
   B=:=B1,
   comuns(C1,C,P1),
   P=:=P1-B.


exactos(X,Y,N):- mesmaposicao(X,Y,0,N).

comuns(X,Y,N):- comuns(X,Y,0,N).

			     

limpa :- abolish(tenta,3).     

anuncio:- findall(X,tenta(X,A,B),L), length(L,N), writeln(['tentativas',N]).

% listas


comuns([],_,N,N).
comuns([X|Xs],Ys,N,M):- member(X,Ys),  N1 is N+1, comuns(Xs,Ys,N1,M).
comuns([X|Xs],Ys,N,M):-  comuns(Xs,Ys,N,M).

mesmaposicao([],[],N,N).
mesmaposicao([X|Xs],[X|Ys],N,M):- N1 is N+1, mesmaposicao(Xs,Ys,N1,M).
mesmaposicao([X|Xs],[Y|Ys],N,M):- X\=Y,  mesmaposicao(Xs,Ys,N,M).


%length([],0).
%length([X|Y],N):- length(Y,N1), N is N1+1.

member(X,[X|_]).
member(X,[_|Y]):- member(X,Y).

selects([],_).
selects([X|Xs],Ys):- delete(X,Ys,Ys1), selects(Xs,Ys1).

delete(X,[X|Y],Y).
delete(X,[Y|Z],[Y|Z1]):- delete(X,Z,Z1).

delete1([X|Xs],X,Xs).
delete1([X|Xs],Z,[X|Y]):- delete1(Xs,Z,Y).
