# How can I count frequency of a list faster?

I have a list

list = RandomInteger[{120, 180}, {20}]


I want to count from the list elements $$a$$ satisfying conditions: $$120\leqslant a <130$$, $$130\leqslant a <140$$, $$120\leqslant a <130$$, $$130\leqslant a <140$$, $$140\leqslant a <150$$, $$150\leqslant a <160$$,$$160\leqslant a <170$$, $$170\leqslant a \leqslant 180$$.

I tried

Clear["Global*"];
list = RandomInteger[{120, 180}, {20}]
h1 = Flatten[SequenceCases[list, {a_} /; 120 <= a < 130], 1]
Length[h1]
h2 = Flatten[SequenceCases[list, {a_} /; 130 <= a < 140], 1]
Length[h2]
h3 = Flatten[SequenceCases[list, {a_} /; 140 <= a < 150], 1]
Length[h3]
h4 = Flatten[SequenceCases[list, {a_} /; 150 <= a < 160], 1]
Length[h4]
h5 = Flatten[SequenceCases[list, {a_} /; 160 <= a < 170], 1]
Length[h5]
h6 = Flatten[SequenceCases[list, {a_} /; 170 <= a <= 180], 1]
Length[h6]


How can I count frequency of a list faster?

• BinCounts[list, {120, 180, 10}] Commented 2 days ago
• I don't think you'll find anything faster than this! Commented 2 days ago
• @xzczd Thank you very much. Commented 2 days ago
• @xzczd BinCounts[list, {120, 180, 10}] doesn't count numbers together as supposed in condition $170\leq a \leq 180$. If there are numbers $180$ they are not counted in. Commented 2 days ago
• @Artes Oh you're right… but wait, OP write 170 <= a < 180 in his code. @minhthien which is the desired condition? Commented 2 days ago

list = {
126, 157, 165, 126, 174,
158, 150, 174, 179, 157,
152, 177, 162, 120, 125,
125, 129, 156, 154, 135
};


A variant using GatherBy and IntegerDigits:

Length /@ GatherBy[Sort@list, Part[IntegerDigits[#], 2] &]


{6, 1, 7, 2, 4}

SortBy[GatherBy[RandomInteger[{120,180},{20}],Floor[#/10]&],Min]

(* {{126,124,125,124},{137},{146,144,145,149},
{154,157,157,157},{164,162,165,168,167},{171,179}} *)

Length /@ %

{4,1,4,4,5,2}


From the question and the sample code, I am not sure how to treat the case of a=180.

I think @xzczd 's suggestion is the fastest but does need a slight adjustment to get the 180 values incorporated.

SeedRandom[12345];
list = RandomInteger[{120, 180}, {100000}];

c = BinCounts[list, {120, 190, 10}];
n = Length[c];
If[c[[n]] == 0, c = c[[1 ;; n - 1]],
c[[n - 1]] = c[[n - 1]] + c[[n]]; c = c[[1 ;; n - 1]]];
c
(* {16174, 16456, 16283, 16595, 16378, 18114} *)
`