I've got a list in the format of list={{a,1},{a,1},{b,1},{c,1},{b,1}}
And I want it to "compress" into a list of pairs {element, frequency} such as this: {{a,2},{b,2},{c,1}}
I've come up with this (faulty) solution:
upravit[l_List] := {l[[1]], l[[2]] + 1}
compression[list_List] :=
list //. {a___, b_List, c_List, d___} /; c[[1]] == b[[1]] -> {a, upravit[b], d}
The problem is that I'm only checking elements that are next to each other, and so in the example, I'd end up with{{a,2},{b,1},{c,1},{b,1}}
Therefore, either I need to correct my code, or come up with an entirely different method (using similar methods thought, as this is a homework).
Thanks for any help!
Edit: as pointed out in the comments and answers, there is a function that easily does that. I should've specified that this should be done using the methods in my example only. Sorry!
Tally[list[[All, 1]]]? – Pinguin Dirk Jan 28 '13 at 11:30Sortyour list before runningcompression? (not sure what you are allowed to do and what not) – Pinguin Dirk Jan 28 '13 at 11:36