Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

Updated:

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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