You actually have two questions, one of the name and the question lurking behind it. The first one answers:
First/@ list
The second, counting the number of runs 1, answered many times, but this solution
Total[Clip[ListCorrelate[{-1, 1},
about 50% faster than Leonid's solution. Note. I increased the length of the test list for better time:
largeTestList = RandomInteger[{0, 1}, {10000000}]; Count[Split[largeTestList], {1 ..}] // AbsoluteTiming Count[Split[largeTestList][[All, 1]], 1] // AbsoluteTiming Total[Clip[Differences@#, {0, 1}]] + First[#] &@ largeTestList // AbsoluteTiming (Tr@Unitize@Differences@# + Tr@#[[{1, -1}]])/2 &@ largeTestList // AbsoluteTiming Total[Clip[ListCorrelate[{-1, 1}, #], {0, 1}]] + First[#] &@ largeTestList // AbsoluteTiming Out[680]= {3.4361965, 2498095} Out[681]= {2.4531403, 2498095} Out[682]= {0.2710155, 2498095} Out[683]= {0.2530145, 2498095} Out[684]= {0.1710097, 2498095}
After the attack of Leonid’s collection, I was going to throw a towel, but I noticed a possible optimization, so the battle goes on ... [Mr.Wizard, Leonid and I should be thrown into jail for breaking the world on SO]
runsOf1Cbis = Compile[{{lst, _Integer, 1}}, Module[{r = Table[0, {Length[lst] - 1}], i = 1, ctr = First[lst]}, For[i = 2, i <= Length[lst], i++, If[lst[[i]] == 1 && lst[[i - 1]] == 0, ctr++; i++]]; ctr], CompilationTarget -> "C", RuntimeOptions -> "Speed"] largeTestList = RandomInteger[{0, 1}, {10000000}]; Total[Clip[ListCorrelate[{-1, 1},
The results are changing, but I get an improvement of 10 to 30%.
Optimization may be difficult to determine, but it is optional i++ if the test {0,1} succeeds. You cannot have two of them in the following places.
And now, the optimization optimization optimization of my optimizer by Leonid (I hope this does not pull, or I will suffer from stack overflow):
runsOf1CDitto = Compile[{{lst, _Integer, 1}}, Module[{i = 1, ctr = First[lst]}, For[i = 2, i <= Length[lst], i++, If[lst[[i]] == 1, If[lst[[i - 1]] == 0, ctr++]; i++]]; ctr], CompilationTarget -> "C", RuntimeOptions -> "Speed"] largeTestList = RandomInteger[{0, 1}, {10000000}]; Total[Clip[ListCorrelate[{-1, 1},
Fortunately for me, Leonid had excessive initialization in his code, which could be removed.