Function Repository Resource:

TrueCountQ

Source Notebook

Determine if the count of elements satisfying a given test at specified levels of an expression falls within a defined range

Contributed by: Phileas Dazeley-Gaist

ResourceFunction["TrueCountQ"][n][{e1,e2,}]

yields True if exactly n elements of the list {e1,e2,} are True.

ResourceFunction["TrueCountQ"][{min,max}][{e1,e2,}]

yields True if between min and max elements of the list {e1,e2,} are True.

ResourceFunction["TrueCountQ"][countspec,test][{e1,e2,}]

yields True if test[ei] is True for a number of elements of {e1,e2,} that satisfies countspec.

ResourceFunction["TrueCountQ"][countspec,test,levelspec][expr]

yields True if test is True for a number of elements of expr that satisfies countspec, with test applied to all parts of expr at levels specified by levelspec.

ResourceFunction["TrueCountQ"][][{e1,e2,}]

yields True if exactly one element of the list {e1,e2,} is True.

Details

The countspec argument can take the following forms:
nexactly n True
{min,max}between min and max True
The countspec argument values can be 0, positive integers, and ∞.
ResourceFunction["TrueCountQ"] uses standard level specifications. See Sequence Specifications.
nlevels 1 through n
Infinitylevels 1 through Infinity
{n}level n only
{n1,n2}levels n1 through n2
ResourceFunction["TrueCountQ"][n,test,levelspec][expr] is equivalent to TrueQ[Length[Cases[Flatten[Map[test,expr,levelspec]],True]]===n].
ResourceFunction["TrueCountQ"][{min,max},test,levelspec][expr] is equivalent to TrueQ[Min[{min,max}]<=Length[Cases[Flatten[Map[test,expr,levelspec]],True]]<=Max[{min,max}]].

Examples

Basic Examples (3) 

Check that exactly 3 elements of a list are odd:

In[1]:=
ResourceFunction["TrueCountQ"][3, OddQ][{1, 4, 9, 16, 25}]
Out[1]=

Check that at least 3 elements of a list are even:

In[2]:=
ResourceFunction["TrueCountQ"][{3, \[Infinity]}, EvenQ][{1, 2, 3, 4, 5, 6}]
Out[2]=

Check that at least 4 cells of a matrix are odd:

In[3]:=
matrix = Array[#1*#2 &, {3, 3}]
Out[3]=
In[4]:=
ResourceFunction["TrueCountQ"][{4, \[Infinity]}, OddQ, {2}][matrix]
Out[4]=

Applications (2) 

Given a binary sequence, determine if at least 3 bits are set to 1:

In[5]:=
binarySequence = {1, 1, 1, 0, 0, 0, 1, 0, 0, 1};
In[6]:=
ResourceFunction[
  "TrueCountQ"][{3, \[Infinity]}, # == 1 &][binarySequence]
Out[6]=

And no more than 4:

In[7]:=
ResourceFunction["TrueCountQ"][{0, 4}, # == 1 &][binarySequence]
Out[7]=

In a game, check if between 3 and 4 four players have reached a target score:

In[8]:=
scores = {10, 15, 20, 25, 30};
In[9]:=
ResourceFunction["TrueCountQ"][{2, 4}, # > 20 &][scores]
Out[9]=

Publisher

Phileas Dazeley-Gaist

Requirements

Wolfram Language 14.0 (January 2024) or above

Version History

  • 1.0.0 – 17 April 2025

Related Resources

License Information