5
$\begingroup$

I have a list that each term consist of two parts. First part is a graph and second is a list of pairs of vertices that I want to find graph distance of.

list={{ImportString[">>graph6<<EK?_"],{{4,5},{2,6},{5,6}}},{ImportString[">>graph6<<HK?g_O?"],{{2,8},{7,8},{8,9}}},{ImportString[">>graph6<<KK?g_O@?_??C"],{{10,11},{10,12},{1,7}}}}

enter image description here

This means I want distances between vertices {4,5}, {2,6} and {5,6} of the first graph and so on...

I want the output in the form:

{{{{4,5},∞},{{2,6},2},{{5,6},∞}},{{{2,8},4},{{7,8},∞},{{8,9},∞}},{{{10,11},∞},{{10,12},∞},{{1,7},2}}}

I can map like GraphDistance[#[[1]],#[[2]]]&/@list but this does not work, of course, because it should be also mapped over #[[2]] like Sequence[#]&/@#[[2]]. I can not figure out how to double-map it.

$\endgroup$
3
  • 3
    $\begingroup$ There are several different approaches you can take. One of them being: Map[d |-> ({{#[[1]], #[[2]]}, GraphDistance[d[[1]], #[[1]], #[[2]]]} & /@ d[[2]]), list] $\endgroup$
    – Domen
    Aug 23, 2022 at 9:59
  • $\begingroup$ How di you do that? :-D It works, but I do not understand how it works. $\endgroup$ Aug 23, 2022 at 10:09
  • 2
    $\begingroup$ @Domen: Your code can be shortened to Map[d|->({#,GraphDistance[d[[1]],Sequence@@#]}&/@d[[2]]),list] $\endgroup$ Aug 23, 2022 at 10:17

3 Answers 3

6
$\begingroup$

I'd say this is the most readable way to do it:

MapApply[
 Function[{graph, vertices},
  MapApply[
   Function[{v1, v2}, {{v1, v2}, GraphDistance[graph, v1, v2]}], 
   vertices
   ]
  ],
 list
]

Note that in versions lower than 13.1, you have to use Apply[f, list, {1}] instead of MapApply[f, list].

$\endgroup$
3
$\begingroup$

Based on @Domen's comment:

list={{ImportString[">>graph6<<EK?_"],{{4,5},{2,6},{5,6}}},{ImportString[">>graph6<<HK?g_O?"],{{2,8},{7,8},{8,9}}},{ImportString[">>graph6<<KK?g_O@?_??C"],{{10,11},{10,12},{1,7}}}};

(d|->{#,GraphDistance[d[[1]],Sequence@@#]}&/@d[[2]])/@list

Clear[list]

(* {{{{4,5},∞]},{{2,6},2},{{5,6},∞}},{{{2,8},4},{{7,8},∞},{{8,9},∞}},{{{10,11},∞},{{10,12},∞},{{1,7},2}}} *)
$\endgroup$
2
$\begingroup$

Using Thread:

Map[{#[[2]], GraphDistance[#[[1]], Sequence @@ #[[2]]]} &, 
 Thread[{#[[1]], #[[2]]}] & /@ list, {2}]
{{{{4, 5}, ∞}, {{2, 6}, 2}, {{5, 6}, ∞}}, {{{2, 8}, 4}, {{7, 8}, ∞}, {{8, 9}, ∞}}, {{{10, 
    11}, ∞}, {{10, 12}, ∞}, {{1, 7}, 2}}}
$\endgroup$

Your Answer

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

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