12
$\begingroup$

Given

    t={{7, 13, 19}, {13, 25, 37}, {19, 37, 55}, {25, 49, 73}, {31, 61, 91}, {37, 73, 109}}

I want to select those lists where all three numbers are primes, so I should get

{{7, 13, 19}, {37, 73, 109}}

I am looking for some equivalent of

Select[PrimeQ] /@ t
Cases[___?PrimeQ] /@ t
Pick[#, PrimeQ@#] &@ t

But these just give me all primes in all sublists.

$\endgroup$

4 Answers 4

14
$\begingroup$

This is a perfect use case for AllTrue:

Select[t, AllTrue[PrimeQ]]
(* {{7, 13, 19}, {37, 73, 109}} *)

Alternatively, you should specify the pattern you actually want in Cases:

Cases[t, {___?PrimeQ}]
(* {{7, 13, 19}, {37, 73, 109}} *)

If for some reason you really want a function you can Map over the list to do what you want, you'll need to use Replace in concert with the special symbol Nothing:

Map[Replace[Except[{___?PrimeQ}] -> Nothing], t]
(* {{7, 13, 19}, {37, 73, 109}} *)
$\endgroup$
6
$\begingroup$
Pick[t, And @@@ PrimeQ @ t]
{{7, 13, 19}, {37, 73, 109}}
$\endgroup$
5
$\begingroup$

Either of these takes advantage of the fact that PrimeQ automatically threads over lists:

Select[t, Apply[And]@*PrimeQ]
Select[t, And @@ PrimeQ[#] &]

(* Out: {7, 13, 19}, {37, 73, 109} *)
$\endgroup$
4
$\begingroup$

I see there are alrready lots of good answers, but my thought was to turn the True and False of the PrimeQ command to 1 and 0, then mutliply:

Extract[t, Position[Times @@@ Boole[PrimeQ[t]], 1]]

{{7, 13, 19}, {37, 73, 109}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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