# How do I utilise distance data from a text file?

I've been given a text file which looks like this -

node0, node1 0.04, node8 11.11, node14 72.21

node1, node46 1247.25, node6 20.59, node13 64.94

Where node0 is the first location, and each subsequent node is a different location, and the number following it is the distance from the first location. I want to utilise this data on a bigger scale to calculate the optimum path between two different locations. How do I go about doing so?

## 1 Answer

\$Version

(* "13.1.0 for Mac OS X x86 (64-bit) (June 16, 2022)" *)

Clear["Global*"]


Import the data

data = Import[
"/Users/roberthanlon/Downloads/nodeData.txt", "Data"]

(* {{"node0,", "node1", "0.04,", "node8", "11.11,", "node14", 72.21},
{"node1,", "node46", "1247.25,", "node6", "20.59,", "node13", 64.94}} *)


Clean up the data

data2 = data /.
str_String :> ToExpression@StringReplace[str, "," -> ""]

(* {{node0, node1, 0.04, node8, 11.11, node14, 72.21},
{node1, node46, 1247.25, node6, 20.59, node13, 64.94}} *)


Restructure the data

helper[{node_, nodes_List}] := Flatten[{node, #}] & /@ nodes

data3 = Flatten[
helper /@ ({#[[1]], Partition[Rest[#], 2]} & /@ data2),
1]

(* {{node0, node1, 0.04}, {node0, node8, 11.11}, {node0, node14, 72.21},
{node1, node46, 1247.25}, {node1, node6, 20.59}, {node1, node13, 64.94}} *)

edges = UndirectedEdge @@ Most[#] & /@ data3;

weights = UndirectedEdge @@ Most[#] -> Last[#] & /@ data3;

gr = Graph[edges, EdgeWeight -> weights,
VertexLabels -> "Name",
EdgeLabels -> "EdgeWeight"]


For your actual graph, then use FindShortestPath`