2
$\begingroup$

Imagine I provide you a list of arbitrary strings, say: Map[StringJoin, Tuples[{"0", "1", "2"}, 4]]. I'd like to abstract these strings as a graph object in Mathematica v9, where each string $s_i$ becomes a vertex $v_i$, and two vertices $(v_a,v_b)$ share an edge if one or more test cases return TRUE for the two strings. For example, if EditDistance[sa,sb] > 3 is TRUE and if StringReverse[sa] == sb is TRUE, then I'd like the respective vertices $v_a$ and $v_b$ to share an edge.

Once I've performed some graph operation to generate a subgraph of the original graph, I'd like to pull back down the list of strings corresponding to the vertices in this subgraph.

Being new to Mathematica v9's treatment of graphs, what would be the best way to proceed here? Is it at all reasonable to do this for large sets of vertices, $10^5$ or so?

$\endgroup$
1
$\begingroup$

Update: In versions 10.2+, you can use RelationGraph

testF2 = UnsameQ[##]&&EditDistance[##] > 3 && StringReverse[#] == #2 &;
Graph[EdgeList[RelationGraph[testF2, vList]], VertexLabels -> "Name"]

enter image description here

Original answer:

vList = Map[StringJoin, Tuples[{"0", "1", "2"}, 4]];
testF = EditDistance[#[[1]], #[[2]]] > 3 && StringReverse[#[[1]]] == #[[2]] &;
e1 = vList[[#]] & /@ (SparseArray[{{i_, j_} /; 
   (i>j&&testF[{vList[[i]], vList[[j]]}]) -> 1}, Length@vList {1, 1}]["NonzeroPositions"]);
(* or *)
e2 = Select[Subsets[vList, {2}], testF];
(* or *)
e3 = With[{vs =Subsets[vList, {2}]}, Pick[vs, testF /@ vs]];
Sort@(Sort /@ e1) == Sort@(Sort /@ e2) == Sort@(Sort /@ e3)
(*True*)
Graph[UndirectedEdge @@@ e1, VertexLabels -> "Name", 
    ImagePadding -> 20] (* Thanks: & @Oska and @BasicCofee *)

enter image description here

e1b = With[{vs = Subsets[vList, {2}]}, 
    Pick[vs, EditDistance[#[[1]], #[[2]]] > 3 & /@ vs]];
{gr, grb} = Graph[UndirectedEdge @@@ #, VertexLabels -> "Name",
     ImagePadding -> 20] & /@ {e1, e1b};
HighlightGraph[grb, gr]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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