CSE505/Assignment2/A/tsp.P
2024-03-09 16:25:30 -05:00

35 lines
1.1 KiB
OpenEdge ABL

/*Jacob Besse
Prolog*/
/*This is the data set.*/
edge(a,b,2). edge(a,c,3). edge(a,d,1).
edge(b,d,2). edge(b,e,2). edge(b,f,4).
edge(c,a,3). edge(c,d,2). edge(c,e,2).
edge(d,a,1). edge(d,b,2).
edge(e,c,2). edge(e,d,2). edge(e,f,1).
edge(f,b,4). edge(f,c,3). edge(f,e,1).
len([], 0).
len([_|T], N):- len(T, X), N is X+1 .
best_path(Visited, Total):- path(a, a, Visited, Total).
path(Start, Fin, Visited, Total) :- path(Start, Fin, [Start], Visited, 0, Total).
path(Start, Fin, CurrentLoc, Visited, Costn, Total) :-
edge(Start, StopLoc, Distance), NewCostn is Costn + Distance, \+ member(StopLoc, CurrentLoc),
path(StopLoc, Fin, [StopLoc|CurrentLoc], Visited, NewCostn, Total).
path(Start, Fin, CurrentLoc, Visited, Costn, Total) :-
edge(Start, Fin, Distance), reverse([Fin|CurrentLoc], Visited), len(Visited, Q),
(Q\=7 -> Total is 100000; Total is Costn + Distance).
shortest_path(Path):-setof(Cost-Path, best_path(Path,Cost), Holder),pick(Holder,Path).
best(Cost-Holder,Bcost-_,Cost-Holder):- Cost<Bcost,!.
best(_,X,X).
pick([Cost-Holder|R],X):- pick(R,Bcost-Bholder),best(Cost-Holder,Bcost-Bholder,X),!.
pick([X],X).