# Quick and efficient way to create graphs from a list of list

I want to generate a list of edges from a list:
(the size of the list can be changed, just 4 for this example)

From the list above, I can generate 24 permutations like this.

mylist = Permutations[{{a, b}, {c, d}, {e, f}, {g, h}}]


Now I want to convert each list in mylist into graph as I mentioned above. I could do this by writing a function like this:

myfunc[{{a_, b_}, {c_, d_}, {e_, f_}, {g_,
h_}}] := {b \[UndirectedEdge] c, d \[UndirectedEdge] e,
f \[UndirectedEdge] g, h \[UndirectedEdge] a};


However, I'm looking for something which is fast, efficient and can work with any number of elements (not just 4 as above).
Any idea to implement this?

Clear[myfunc];

myfunc[list_] :=
UndirectedEdge @@@ Partition[RotateLeft[Flatten[list], 1], 2]

myfunc /@ mylist
(* { {b \[UndirectedEdge] c, d \[UndirectedEdge] e, f \[UndirectedEdge] g,
h \[UndirectedEdge] a}, ...} *)

• I think you misread my rule to convert the list to graph. {{a, b}, {c, d}} would be converted to {b-c, d-a} with- is for undirected edge. Nov 3, 2022 at 22:27
• Oh, sorry I had two functions with the same name so it was confusing. Nov 3, 2022 at 22:32
• It does that, but it was meant to accept the whole mylist. I changed it now to a single-list function. Nov 3, 2022 at 22:32
• Simplifying: UndirectedEdge @@@ Partition[RotateLeft@Catenate@#, 2] &
– Alan
Nov 4, 2022 at 21:51

Or using SubsetMap. After we get one graph, we use Permutations to act on it to get anoter cases.

Clear[list,graph];
list = {{a, b}, {c, d}, {e, f}, {g, h}};
graph = UndirectedEdge @@@
Reverse /@ SubsetMap[RotateLeft, list, {All, 1}]

graph // Permutations


just for fun.

{{a, b}, {c, d}, {e, f}, {g, h}} //
# /. {a_, e___} -> {a, e, a}& //
# //.{x___UndirectedEdge, {a_,b_},{c_,d_},e___} -> {x, UndirectedEdge[b,c], {c,d} ,e}& //
# /. {e___, a_} -> {e}&


{UndirectedEdge[b, c], UndirectedEdge[d, e], UndirectedEdge[f, g], UndirectedEdge[h, a]}

list = {{a, b}, {c, d}, {e, f}, {g, h}};


MapThread[UndirectedEdge]@Reverse@MapAt[RotateRight, 2]@Transpose@list


Visualizing the code with Echo:

MapThread[UndirectedEdge]@
Echo@Reverse@Echo@MapAt[RotateRight, 2]@Echo@Transpose@Echo@list


list

$$\left( \begin{array}{cc} a & b \\ c & d \\ e & f \\ g & h \\ \end{array} \right)$$

Transpose

$$\left( \begin{array}{cccc} a & c & e & g \\ b & d & f & h \\ \end{array} \right)$$

MapAt[RotateRight, 2]

$$\left( \begin{array}{cccc} a & c & e & g \\ h & b & d & f \\ \ & \longrightarrow \end{array} \right)$$

Reverse

$$\left( \updownarrow \begin{array}{cccc} h & b & d & f \\ a & c & e & g \\ \end{array} \right)$$

$$\{h\longleftrightarrow a,b\longleftrightarrow c,d\longleftrightarrow e,f\longleftrightarrow g\}$$
Note : I used /. UndirectedEdge -> LongLeftRightArrow as UndirectedEdge does not render well here.