%%% 13.11.2010

%% Task 1, group 2
% X - list of lists of numbers
% Y - list of numbers

% is_member(E, L) :- checks if E is element of L
is_member(X, [X|_]).
is_member(X, [_|T]) :- is_member(X, T).

% min_element(M, L) :- M is the minimal element of the list L
min_element(H, [H]).
min_element(H, [H|T]) :- min_element(Y, T), H =< Y.
min_element(Y, [H|T]) :- min_element(Y, T), Y < H.

% get_min_values(M, X) :- M is a list with the min value from each sublist of X
get_min_values([], []).
get_min_values([M|L], [H|T]) :- min_element(M, H), get_min_values(L, T).

%% is_perm(L, M) :- Checks if L is a permutation of M
is_perm([], []).
is_perm([H|T], M) :- is_member(H, M), remove_element(H, M, N), is_perm(T, N).

% list_length(L, N) :- Finds the length N of the list L
list_length([], 0).
list_length([_|T], N) :- list_length(T, N1), N is N1 + 1.

%% sublist(L, M) :- Checks if L is a sublist of M
sublist(L, M) :- not((is_member(E, L), not(is_member(E, M)))).

% meet_condition(X, Y) :- Checks if X meets the given condition
meet_condition(X, Y) :- get_min_values(M, X),
						sublist(Y, M). 								%% or is_perm(Y, M)?

p(X, Y) :- is_member(Y, X), meet_condition(Y, X), list_length(Y, N1),
		   not((
		   		is_member(Z, X),
		   		meet_condition(Z, X),
		   		list_length(Z, N2),
		   		N2 < N1
		   	  )).


%% NOT WORKING