From 48c1baf230a1581e1e4a2a3b51dbe5c9ee920821 Mon Sep 17 00:00:00 2001 From: fredrikr79 Date: Wed, 5 Nov 2025 12:39:14 +0100 Subject: [PATCH] ex5: finish, gather `handin.pl` --- assignment5/handin.pl | 48 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 assignment5/handin.pl diff --git a/assignment5/handin.pl b/assignment5/handin.pl new file mode 100644 index 0000000..4116053 --- /dev/null +++ b/assignment5/handin.pl @@ -0,0 +1,48 @@ +% task 1 + +payment(Sum, Coins) :- + payment_acc(0, Sum, Coins). + +payment_acc(Acc, Sum, []) :- + Acc #= Sum. + +payment_acc(Acc, Sum, [coin(Count, Value, Available)|Tail]) :- + Count in 0..Available, + NewAcc #= Acc + Count * Value, + payment_acc(NewAcc, Sum, Tail). + +% task 2.1 + +distance(c1, c2, 10, 1). distance(c1, c3, 0, 0). distance(c1, c4, 7, 1). +distance(c1, c5, 5, 1). distance(c2, c3, 4, 1). distance(c2, c4, 12, 1). +distance(c2, c5, 20, 1). distance(c3, c4, 0, 0). distance(c3, c5, 0, 0). +distance(c4, c5, 0, 0). distance(c2, c1, 10, 1). distance(c3, c1, 0, 0). +distance(c4, c1, 7, 1). distance(c5, c1, 5, 1). distance(c3, c2, 4, 1). +distance(c4, c2, 12, 1). distance(c5, c2, 20, 1). distance(c4, c3, 0, 0). +distance(c5, c3, 0, 0). distance(c5, c4, 0, 0). + +% arity 4 predicate +plan(Cabin1, Cabin2, Path, TotalDistance) :- + plan(Cabin1, Cabin2, [Cabin1], Path, TotalDistance). + +% base case +plan(Cabin1, Cabin2, Visited, Path, Distance) :- + not(Cabin1 = Cabin2), + distance(Cabin1, Cabin2, Distance, 1), + append(Visited, [Cabin2], Path). + +% recursive case +plan(Cabin1, Cabin2, Visited, Path, TotalDistance) :- + not(Cabin1 = Cabin2), + distance(Cabin1, CabinX, Distance, 1), + \+ member(CabinX, Visited), + append(Visited, [CabinX], NewVisited), + plan(CabinX, Cabin2, NewVisited, Path, SubDistance), + TotalDistance is Distance + SubDistance. + +% task 2.2 + +bestplan(Cabin1, Cabin2, ShortestPath, ShortestDistance) :- + findall([Path, Distance], (plan(Cabin1, Cabin2, Path, Distance)), Solutions), + sort(2, @=<, Solutions, [ShortestSolution|_]), + [ShortestPath, ShortestDistance] = ShortestSolution.