Skip to main content
4 of 4
added 139 characters in body
LLlAMnYP
  • 11.5k
  • 27
  • 66

The previous answers seem to have been addressing a rather different (or much more generalized) sort of problem, because as I see this now, we have the following problem statement:

len = 10; (* let's have 10 to be specific, but this is an arbitrary positive integer *)
max = 10^3; (* maximum value of numbers in listB *)
listA = Range[len];
listB = RandomInteger[{1, max}, len];

Then of course a member of listB is a member of listA if it is less than (or equal to) len. So to get the matching numbers we do:

Pick[listB, # <= len &/@ listB]
(* {2, 10, 2, 5, 7, 7} *)

And to get the count of that, simply

Length@%
(* 6 *)

This is slower than @ciao's answer. However, this is almost 2 orders of magnitude faster:

Pick[listB, Sign[listB - len - 1], -1]

And this one is a tiny bit slower, but slightly more general (handles negative integers properly):

Pick[listB, Quotient[listB, len, 1], 0]

Here are the timings for the solutions:

len = 1000000;
max = 10000000;
listA = Range[len];
listB = RandomInteger[{1, max}, len];
(Tr[Tally[#1~Join~#2][[;; Length@#1, 2]]] - Length[#1]) &[listA, 
   listB] // AbsoluteTiming // First
Pick[listB, # <= len & /@ listB] // AbsoluteTiming // First
Pick[listB, Sign[listB - len - 1], -1] // AbsoluteTiming // First
Pick[listB, Quotient[listB, len, 1], 0] // AbsoluteTiming // First

0.556392 (* ciao *)
0.803501 (* boolean comparison *)
0.0136436 (* Sign *)
0.0171063 (* Quotient *)

Be aware, that while my solution is easily adaptable to the variations of the problem, as stated right now, if listA is also to have random numbers, as originally suggested, ciao's way is probably the fastest (and IMO, really elegant).

LLlAMnYP
  • 11.5k
  • 27
  • 66