Find minimum of various predicates

Viewed 158

I want to find the minimum value of all permutations called from main predicate. For simplicity, I have removed my entire code, assume that I just want to find the minimum of head elements of all permutations.

appendlist([], X, X).
appendlist([T|H], X, [T|L]) :- appendlist(H, X, L).

permutation([], []).
permutation([X], [X]) :-!.
permutation([T|H], X) :- permutation(H, H1), appendlist(L1, L2, H1), appendlist(L1, [T], X1), appendlist(X1, L2, X).

%min(X, A, B) X is the minimum of A, B
min(X, X, Y) :- X =< Y.
min(Y, X, Y) :- Y < X.

solve([Head|Rest], Head):-
   writeln([Head|Rest]).

main :-
   Sort = [1, 2, 3],
   PrvAns is 1000,
   permutation(Sort, X),
   solve(X, Here),
   min(Ans, Here, PrvAns),
   writeln(Ans),
   PrvAns = Ans,
   !, fail;
   true,
   writeln(PrvAns).

I want to calculate the minimum on fly for each permutation. Now, permute is working fine, and you can see that solve prints all permutations and even returns the first value Head properly, but PrvAns = Ans is wrong.

Expected output PrvAns : 1

1 Answers

I'm sorry if I didn't understand properly (and tell me, so I can help you), but, you mean something like this?

    findMinHead(X,Z):-
        findall( Y, ( permutation(X,[Y|_]) ), Z1 ),
        min_list(Z1,Z).

in this predicate we find all the Y values where Y is the head of a permutation of X, put all that values in a bag, and then find the min.

Related