1
$\begingroup$

Some weeks ago, I posted a question which involved creating string pairs from a list of string elements. One of the answers posted (by Kuba) worked very well until I found an example where it didn't. Here it is:

lis = {"ABCDEFGHI" | "JKLMN OP" | "PQR" | "JKLMN" | "OPXYZ"};
prs = {"JKLMN OP ABCDEFGHI", "JKLMN OPXYZ", "PQR JKLMN"};

Given the list prs whose elements consist of two members of lis separated by a space, the task is to create a modified prs where the elements of prs are separated into two elements that are members of lis.

Kuba's suggestion was essentially:

separatedNames = Table[StringSplit[prs[[i]]], {i, Length[prs]}];
alternative = Apply[Alternatives]@Reverse@SortBy[StringLength]@lis[[1]];
res = Partition[Flatten[StringCases[alternative] /@ StringRiffle /@ separatedNames],2]

This produces: {{"JKLMN OP", "ABCDEFGHI"}, {"JKLMN OP", "PQR"}}

and not the desired: {{"JKLMN OP","ABCDEFGHI"},{"JKLMN","OPXYZ"},{"PQR","JKLMN"}}

As always thanks for thoughts.

$\endgroup$
1
$\begingroup$
as = Association[StringRiffle@#->#&/@(Join[#, Reverse/@#]&@Subsets[List @@ lis[[1]], {2}])]

as[[prs]]

<|"JKLMN OP ABCDEFGHI" -> {"JKLMN OP", "ABCDEFGHI"}, "JKLMN OPXYZ" -> {"JKLMN", "OPXYZ"}, "PQR JKLMN" -> {"PQR", "JKLMN"}|>

as /@ prs

{{"JKLMN OP", "ABCDEFGHI"}, {"JKLMN", "OPXYZ"}, {"PQR", "JKLMN"}}

$\endgroup$
  • $\begingroup$ Thank you, kglr, that works well. $\endgroup$ – Suite401 Nov 13 '18 at 16:11
  • $\begingroup$ a question: It would be desirable to preserve the order of the pairs in the output of assoc/@prs to be the same as in prs (i.e., the first element would be {"JKLMN OP","ABCDEFGHI"} and not {"ABCDEFGHI","JKLMN OP"}. Thanks $\endgroup$ – Suite401 Nov 25 '18 at 21:39
  • $\begingroup$ @Suite401, good point. I will update if i can find a solution. $\endgroup$ – kglr Nov 25 '18 at 23:38
  • $\begingroup$ That would be very helpful, thank you. $\endgroup$ – Suite401 Dec 9 '18 at 8:17
  • $\begingroup$ @Suite401, updated. $\endgroup$ – kglr Dec 9 '18 at 9:04

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.