# Counting the number of occurrences of specific values in a list in specific intervals

If the variable "digits" contains 10,000 digits from 0 to 9. How can the number of occurrences of 1s and 2s be counted in every 1000 digit intervals, that is to say the number of 1s and 2s from 1 to 1000, the number of 1s and 2s from 1001 to 2000 and so on.

• Seem a little strange advice, but you could use the capability of Mathematica in String Manipulation with StringCount for example. Jul 6, 2020 at 19:41
• {Count[#, 1], Count[#, 2]} & /@ Partition[digits, 1000] Jul 6, 2020 at 19:47

Does "contains" mean it is a list, or a string, or a long integer? You use the list-manipulation tag, so presumably a list. If you want the total, you can

Count[1|2] /@ Partition[digits, 1000]


Using a smaller example (with the list digits having 20 elements instead of 10000 and block size 5 instead of 1000):

n = 20;
bs = 5;

SeedRandom[1]
digits = RandomInteger[9, n]
{1, 4, 0, 7, 0, 0, 8, 6, 0, 4, 1, 8, 5, 1, 1, 1, 3, 2, 1, 6}


You can use BlockMap in combination with Counts, Tally, Count or BinCounts as follows:

BlockMap[Counts, digits, bs]

{<|1 -> 1, 4 -> 1, 0 -> 2, 7 -> 1|>,
<|0 -> 2, 8 -> 1, 6 -> 1,  4 -> 1|>,
<|1 -> 3, 8 -> 1, 5 -> 1|>,
<|1 -> 2, 3 -> 1, 2 -> 1, 6 -> 1|>}

BlockMap[Tally, digits, bs]

{{{1, 1}, {4, 1}, {0, 2}, {7, 1}},
{{0, 2}, {8, 1}, {6, 1}, {4, 1}},
{{1, 3}, {8, 1}, {5, 1}},
{{1, 2}, {3, 1}, {2, 1}, {6, 1}}}


If a list of counts for each number from 0 to 9 in each block is desired:

BlockMap[Counts[#] /@ Range[0, 9] /. Missing -> (0 &) &, digits, bs]

{{2, 1, 0, 0, 1, 0, 0, 1, 0, 0},
{2, 0, 0, 0, 1, 0, 1, 0, 1, 0},
{0, 3, 0, 0, 0, 1, 0, 0, 1, 0},
{0, 2, 1, 1, 0, 0, 1, 0, 0, 0}}

BlockMap[Through[(Count /@ Range[0, 9])@#] &, digits, bs]

{{2, 1, 0, 0, 1, 0, 0, 1, 0, 0},
{2, 0, 0, 0, 1, 0, 1, 0, 1, 0},
{0, 3, 0, 0, 0, 1, 0, 0, 1, 0},
{0, 2, 1, 1, 0, 0, 1, 0, 0, 0}}

BlockMap[BinCounts[#, {0, 10, 1}] &, digits, bs]

{{2, 1, 0, 0, 1, 0, 0, 1, 0, 0},
{2, 0, 0, 0, 1, 0, 1, 0, 1, 0},
{0, 3, 0, 0, 0, 1, 0, 0, 1, 0},
{0, 2, 1, 1, 0, 0, 1, 0, 0, 0}}