Intersection works as expected in this case...
a = Range[1,5];b=Range[3,7]; Intersection[a,b] giving...
{3,4,5} However if I expand the concept of sameness using SameTest to this...
Intersection[a,b, SameTest->(Abs[#1-#2]<=1&)] I get the slightly puzzling result of...
{5} I was expecting to see something like {2,3,4,5,6}.
I thought this might be Union running within Intersection but...
Union[{2,3,4,5,6},SameTest->(Abs[#1-#2]<=1&)] gives...
{2,4,6} So I am at something of a loss.
Part II
Given the comments below, clearly Intersection isn't going to give me what I want, which is
- every element from list a that is within some given distance of any element within list b. and
- every element from list b that is within some given distance of any element within list a.
I can do this with something ugly like...
Union[Flatten[Select[Apply[Join, Outer[List, a, b]], Abs[{1, -1}.#] <= 1 &]]] But the Outer is likely to bite hard with big lists.
Any improvements spring to mind?
#1in both cases. In general, your sameness function is not transitive (meaning that froma ~ bandb ~ cdoes not followa ~ cin general, where I used~to denote sameness function), so you may expect different results depending on the order in which things are compared. So, you should either use a transitive sameness function, or rely on a particular order of comparisons, if you want predictable and deterministic results. $\endgroup$Complement,Intersection,Unionetc. treat lists as sets. Which means that they are probably inappropriate for your needs, unless you manage to reformulate your problem to use a transitive sameness function. $\endgroup$