Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count occurrences of elements [duplicate]

Counting all elements in a list is a one-liner in Haskell:

count xs = toList (fromListWith (+) [(x, 1) | x <- xs])

Here is an example usage:

*Main> count "haskell scala"
[(' ',1),('a',3),('c',1),('e',1),('h',1),('k',1),('l',3),('s',2)]

Can this function be expressed so elegantly in Scala as well?

like image 884
fredoverflow Avatar asked Jun 07 '12 14:06

fredoverflow


People also ask

How do I count occurrence of duplicate items in array?

To count the duplicates in an array: Declare an empty object variable that will store the count for each value. Use the forEach() method to iterate over the array. On each iteration, increment the count for the value by 1 or initialize it to 1 .

How do you count repeated elements in Python?

Operator. countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value. It returns the Count of a number of occurrences of value.

How do you count duplicates in Excel?

Tip: If you want to count the duplicates in the whole Column, use this formula =COUNTIF(A:A, A2) (the Column A indicates column of data, and A2 stands the cell you want to count the frequency, you can change them as you need).


3 Answers

scala> "haskell scala".groupBy(identity).mapValues(_.size).toSeq
res1: Seq[(Char, Int)] = ArrayBuffer((e,1), (s,2), (a,3), ( ,1), (l,3), (c,1), (h,1), (k,1))
like image 179
missingfaktor Avatar answered Oct 20 '22 16:10

missingfaktor


Recall group from the Data.List library,

group :: [a] -> [[a]]

giving us:

map (head &&& length) . group . sort

a list-friendly and relatively "naive" implementation.

like image 20
Don Stewart Avatar answered Oct 20 '22 17:10

Don Stewart


Another implementation:

def count[A](xs: Seq[A]): Seq[(A, Int)] = xs.distinct.map(x => (x, xs.count(_ == x)))
like image 33
thSoft Avatar answered Oct 20 '22 17:10

thSoft