2
$\begingroup$

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.

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

2 Answers 2

3
$\begingroup$

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]
$\endgroup$
1
$\begingroup$

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}}
$\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.