0
$\begingroup$

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?

$\endgroup$
2

1 Answer 1

4
$\begingroup$
$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"]

enter image description here

For your actual graph, then use FindShortestPath

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.