Count the times a digit has appeared in a list as I scan the list
cnts = Transpose[{#, Module[{o = Ordering@#},
o[[o]] = Join @@ Range@Tally[#[[o]]][[All, 2]]; o]}] &;
Use (l containing desired list target):
result=cnts@l;
Will be order(s) of magnitude faster on large lists than OP method.
Here is a semi-imperative method:
runningCount[list_] := Module[{c}, c[_] = 0; {#, ++c[#]} & /@ list]
Example:
runningCount[{4, 2, 4, 0, 1, 0, 0, 2, 0, 0}]
(* {{4, 1}, {2, 1}, {4, 2}, {0, 1}, {1, 1}, {0, 2}, {0, 3}, {2, 2}, {0, 4}, {0, 5}} *)
I'll join the party :)
Clear["Global`*"]
lst = {4, 2, 4, 0, 1, 0, 0, 2, 0, 0};
Scan[(x[#] = 0) &, Union[lst]];
(Last@Reap@Scan[ Sow[{#, ++x[#]} ] &, lst])[[1]]
The idea is to set up a hash lookup counter of each number in the list, initially at zero. Then scan the list, incrementing the counter by one using lookup each time.
Timings
I did basic timings for the solutions given. all are using this list, and using AbsoluteTiming
command
lst = RandomInteger[10000, 50000];
Result
Ciao solution: 0.015831 seconds
W Reach solution: 0.15155 seconds
Nasser solution: 0.22417 seconds
David Keith solution: 2.3196 seconds
A.G. solution: 145.95 seconds
Code
Clear["Global`*"]
SeedRandom[1]
lst = RandomInteger[10000, 50000];
AbsoluteTiming[
Scan[(x[#] = 0) &, Union[lst]];
(Last@Reap@Scan[Sow[{#, ++x[#]}] &, lst])[[1]];
]
Clear["Global`*"]
SeedRandom[1]
lst = RandomInteger[10000, 50000];
AbsoluteTiming[
Table[First@Tally@Reverse@Take[lst, i], {i, 1, Length@lst}];]
Clear["Global`*"]
SeedRandom[1]
lst = RandomInteger[10000, 50000];
counts[l_] :=
Table[{l[[n]], Count[l[[1 ;; n]], l[[n]]]}, {n, Length[l]}]
AbsoluteTiming[counts[lst];]
Clear["Global`*"]
SeedRandom[1]
lst = RandomInteger[10000, 50000];
cnts = Transpose[{#,
Module[{o = Ordering@#},
o[[o]] = Join @@ Range@Tally[#[[o]]][[All, 2]]; o]}] &;
AbsoluteTiming[cnts@lst;]
Clear["Global`*"]
SeedRandom[1]
lst = RandomInteger[10000, 50000];
runningCount[list_] := Module[{c}, c[_] = 0; {#, c[#] += 1} & /@ list]
AbsoluteTiming[runningCount[lst];]