Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find most common string in an array

Tags:

I have this array, for example (the size is variable):

   x = ["1.111", "1.122", "1.250", "1.111"]

and I need to find the most commom value ("1.111" in this case).

Is there an easy way to do that?

Tks in advance!


EDIT #1: Thank you all for the answers!


EDIT #2: I've changed my accepted answer based on Z.E.D.'s information. Thank you all again!

like image 481
Ju Nogueira Avatar asked Apr 01 '10 17:04

Ju Nogueira


People also ask

How do you find the most repeated string in an array?

More simple solution is to use HashMap. Approach: Using HashMap, one can keep track of word and it's frequency. Next step includes iterate over it and find out the word with maximum frequency. Below is the implementation of the above approach.

How do you find the most common value in an array?

Steps to find the most frequency value in a NumPy array:Create a NumPy array. Apply bincount() method of NumPy to get the count of occurrences of each element in the array. The n, apply argmax() method to get the value having a maximum number of occurrences(frequency).


1 Answers

Ruby < 2.2

#!/usr/bin/ruby1.8

def most_common_value(a)
  a.group_by do |e|
    e
  end.values.max_by(&:size).first
end

x = ["1.111", "1.122", "1.250", "1.111"]
p most_common_value(x)    # => "1.111"

Note: Enumberable.max_by is new with Ruby 1.9, but it has been backported to 1.8.7

Ruby >= 2.2

Ruby 2.2 introduces the Object#itself method, with which we can make the code more concise:

def most_common_value(a)
  a.group_by(&:itself).values.max_by(&:size).first
end

As a monkey patch

Or as Enumerable#mode:

Enumerable.class_eval do
  def mode
    group_by do |e|
      e
    end.values.max_by(&:size).first
  end
end

["1.111", "1.122", "1.250", "1.111"].mode
# => "1.111"
like image 99
Wayne Conrad Avatar answered Sep 30 '22 16:09

Wayne Conrad