Mode

I bet there’s a more elegant way to write this. Anyone want to show me?

def mode(li)
best_num = nil
best_count = -1
li.uniq.each do |item|
count = (li.select { |item2| item == item2}).length
if count > best_count
best_count = count
best_num = item
end
end
best_num
end

– Elliot T.

On 6/5/06, Elliot T. [email protected] wrote:

 end

li.uniq.collect {|i| [li.select {|j| j == i}.size, i]}.sort.last.last

-----Original Message-----
From: Elliot T. [mailto:[email protected]]

I bet there’s a more elegant way to write this. Anyone want
to show me?

def mode(li)

end

It would probably help if you said what you were trying to achieve
rather than asking people to try and interpret code that you admit isn’t
elegant.

class Array
def mode
count = Hash.new(0)
each {|x| count[x] += 1 }
count.sort_by{|k,v|v}.last[0]
end
end

On Jun 4, 2006, at 11:31 PM, Alder G. wrote:

li.uniq.collect {|i| [li.select {|j| j == i}.size, i]}.sort.last.last

cool, thanks, collecting pairs works well.

On Jun 4, 2006, at 11:40 PM, Daniel S. wrote:

It would probably help if you said what you were trying to achieve
rather than asking people to try and interpret code that you admit
isn’t
elegant.

Mode means:

(Statistics) the value that occurs most frequently in a given set of
data.

class Array
def mode
count = Hash.new(0)
each {|x| count[x] += 1 }
count.sort_by{|k,v|v}.last[0]
end
end

that’s a nice way :slight_smile:

– Elliot T.

Hi Micheal,

I could not get your example to work properly. It seemed to return the
count of the highest number in my initial list.

I modified it to

li.inject(Hash.new(0)){|s,v| s[v] += 1; s}.invert.max.last

and it gave me the result I expected. Is it just me tho?

li.inject(Hash.new(0)){|s,v| s[v] += 1; s}.max.last

count of the highest number in my initial list.

I modified it to

li.inject(Hash.new(0)){|s,v| s[v] += 1; s}.invert.max.last

and it gave me the result I expected. Is it just me tho?

another one:

li.sort_by{|x| li.select{|y| x==y}.length}.last

cheers

Simon

another one:

li.sort_by{|x| li.select{|y| x==y}.length}.last

even better (if === does what you expect)

li.sort_by{|x|li.grep(x).size}.last

Hi,

“Kroeger, Simon (ext)” [email protected] writes:

li.sort_by{|x|li.grep(x).size}.last

In 1.9, you can use Enumerable#max_by.

li.max_by{|x|li.grep(x).size}