Hello,
we have to solve the knapsack problem in Prolog at the university. We have the source code as a solution, but we have to explain it.
Can someone explain the functions to me?
Thank you very much.
I’m using: SWI-Prolog version 8.0.2
My code :
item(1,12,4).
item(2,2,2).
item(3,2,1).
item(4,1,1).
item(5,4,10).
weight([],0).
weight([item(,W,) | Rest], X) :-
weight(Rest,RestW),
X is W + RestW.
value([],0).
value([item(,,V) | Rest], X) :-
value(Rest,RestV),
X is V + RestV.
subseq([],[]).
subseq([Item | RestX], [Item | RestY]) :-
subseq(RestX,RestY).
subseq(X, [_ | RestY]) :-
subseq(X,RestY).
legalKnapsack(Number,Capacity,Knapsack):-
subseq(Knapsack,Number),
weight(Knapsack,W),
W =< Capacity.
allLegalKnapsacks(Number,Capacity,ListOfLegalKnapsacks) :-
findall(LegalKnapsack, legalKnapsack(Number,Capacity,LegalKnapsack), ListOfLegalKnapsacks).
maximumValue([LEGAL | LEGALS], MAXVAL) :- value(LEGAL, VAL), maxVal(LEGALS, VAL, LEGAL, MAXVAL).
maxVal([], MAXVAL, MAXVALLEGAL,MAXVALLEGAL).
maxVal([LEGAL | LEGALS], MAXVAL, MAXVALLEGAL, OUTPUT) :- value(LEGAL, NEWVAL), NEWVAL > MAXVAL,
maxVal(LEGALS, NEWVAL, LEGAL, OUTPUT).
maxVal([LEGAL | LEGALS], MAXVAL, MAXVALLEGAL, OUTPUT) :- value(LEGAL, NEWVAL), NEWVAL =< MAXVAL,
maxVal(LEGALS, MAXVAL, MAXVALLEGAL, OUTPUT).
knapsackOptimization(Number, Capacity, Knapsack) :- allLegalKnapsacks(Number, Capacity, R),
maximumValue(R, Knapsack),
value(Knapsack, VAL),print(’\n’),print('Value: '), print(VAL).