Stats

Popular Posts

Followers

Mathematica 教學:Tikz Plot for Traveling Salesman Problem

戴忠淵 於 2025年7月16日星期三 下午10:57 發表
pathtikz[tour_,coords_]:=Block[{nodeStrings,nodeBlock,pathString,startNode},
startNode=tour[[1]];

(*節點資料字串*)
nodeStrings=MapIndexed[StringTemplate["``/``/``/``,\n"]@@
{tour[[#2[[1]]]],#[[1]],#[[2]],If[#2[[1]]==1,"green","red"]}&,coords];

(*把最後一個的逗號拿掉*)
nodeBlock=StringJoin@Riffle[Most[nodeStrings],""]<>
StringReplace[Last[nodeStrings],",\n"->"}"];

(*路徑字串*)
pathString=StringJoin[Riffle["("<>ToString[#]<>")"&/@tour,"--"]];

pathString=pathString<>"--(1);";

(*組合 TikZ code*)
latexCode=StringTemplate["
\\begin{minipage}{\\linewidth}
\\centering
\\textbf{圖:最佳TSP巡迴路徑} \\\\[0.5em]
\\fbox{%
\\begin{tikzpicture}[scale=0.08]

% 節點座標與顏色:第1個為綠色,其餘為紅色
\\foreach \\i/\\x/\\y/\\c in {
``
{
  \\node[draw, circle, fill=\\c, inner sep=2pt] (\\i) at (\\x,\\y) {};
  \\node[font=\\tiny] at (\\x + 2, \\y + 2) {\\i};
}

% 最佳路徑
  \\draw[blue, thick]
  ``
  \\end{tikzpicture}
}
\\end{minipage}
"][nodeBlock,pathString]]

test = RandomReal[{0, 100}, {50, 2}];
ans = FindShortestTour[test];

tour = ans[[2]][[1 ;; -2]];
coords = test[[tour]];

pathtikz[tour, coords]
Tags:

讀者回應 ( 0 意見 )

發佈留言

Please leave your name and tell me what you thought about this site. Comments, suggestions and views are welcomed.

如果這篇文章對你有幫助,那請留個訊息給我~