/*********************************************************** tsp_cp2.pi from Constraint Solving and Planning with Picat, Springer by Neng-Fa Zhou, Hakan Kjellerstrand, and Jonathan Fruhman ***********************************************************/ import cp. main => M = {{0,6,1,5,0,0}, % cost matrix {6,0,5,0,3,0}, {1,5,0,5,6,4}, {5,0,5,0,0,2}, {0,3,6,0,0,6}, {0,0,4,2,6,0}}, tsp(M). tsp(M) => N = length(M), NextArr = new_array(N), % visit NextArr[I] after I NextArr :: 1..N, CostArr = new_array(N), circuit(NextArr), foreach (I in 1..N) CostArr[I] #> 0, element(NextArr[I],M[I],CostArr[I]) end, TotalCost #= sum(CostArr), foreach (I in 1..N) Pairs = [(M[I,J],J) : J in 1..N, M[I,J] > 0].sort(), Neibs = [J : (_,J) in Pairs], NextArr[I].put_attr(domain,Neibs) end, solve(\$[min(TotalCost), label(mylabel), report(println(cost=TotalCost))], NextArr), foreach (I in 1..N) printf("%w -> %w\n",I,NextArr[I]) end. mylabel(V),var(V) => Domain = V.get_attr(domain), member(V,Domain). mylabel(_V) => true.