Re: Match Pairs of Numbers

*To*: mathgroup at smc.vnet.net*Subject*: [mg86907] Re: Match Pairs of Numbers*From*: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>*Date*: Wed, 26 Mar 2008 04:48:47 -0500 (EST)*Organization*: The Open University, Milton Keynes, UK*References*: <fsa5bn$aae$1@smc.vnet.net>

Andrew Beveridge wrote: > I am having trouble finding the correct form of Pattern Matching for > pairs of Numbers. I do not know whether to use Select, Cases, Pick, > etc. I am also unsure how to set the pattern matching argument. > > Assume I have the list > > lst = {{1,1}, {1,2}, {1,3}, {1,4}, {2,2}, {3,1}, {3,2}, {3,3}, {4,1}, {4,4}} > > > I would like to match/select pairs that have the same set of numbers > only reversed, that is, the selection would find > > {{1,3}, {3,1}, {1,4}, {4,1} } The following examples should help you started. Note that they have not been optimized for speed, though the recursive example (myComp) is much faster than the first one (which try to illustrate how to use Pick). Also, note that the best strategy to solve the problem depends on many factors you did not mention, such as the size of the list, possibility of many occurrences of matching pairs (say, several {1,4}'s), whether the order of the matching pairs returned in the solution is important, etc. lst = {{1,1},{1,2},{1,3},{1,4},{2,2},{3,1},{3,2},{3,3},{4,1},{4,4}}; myCheck[lst_List] := Module[{rev = Reverse /@ lst}, Flatten[Table[ Pick[lst, MapThread[SameQ, {lst, RotateLeft[rev, n]}]], {n, Length@lst - 1}] /. {} -> Sequence[], 1]] myCheck[lst] (* ==> {{1, 3}, {1, 4}, {4, 1}, {3, 1}} *) myComp[data_List] := Module[{mySearch}, mySearch[pair_List, lst_List /; Length[lst] > 0] := Union[Cases[Reverse /@ lst, pair], mySearch[First@lst, Rest@lst]]; mySearch[pair_List, lst_List] := {}; Block[{$RecursionLimit = 10 + Length@data}, mySearch[First@lst, Rest@lst] ] ] myComp[lst] (* ==> {{1, 3}, {1, 4}} *) Regards, -- Jean-Marc