1

I have a list that I need to sort by the most popular elements. Is there a method to accomplish that?

After I re-sort it, I also need to get rid of duplicates. I have an idea of a function in my mind for this but it seems inefficient, so are there built-in methods to help with this?

5 Answers 5

4
[1,5,4,6,4,1,4,5].group_by {|x| x}.sort_by {|x,list| [-list.size,x]}.map(&:first)
=> [4,1,5,6]

Like that?

Sign up to request clarification or add additional context in comments.

Comments

3

The Array#sort method takes an optional predicate to compare two elements, so...

list.sort { |a, b| a.popularity <=> b.popularity }

To eliminate duplicates, use Array#uniq.

list.uniq

To glue them together,

list = list.sort { |a, b| a.popularity <=> b.popularity }.unique

Or simply

list.sort! { |a, b| a.popularity <=> b.popularity }.uniq!

Comments

0

Iterating through the list to build a hash that maps item -> number of times just need one visit of all elements of the list, then operations with the hash would be constant time, so O(n), that doesn't seem so expensive.

Comments

0

The uniq method takes a block, so you can specify which 'property' of your object has to be uniq.

new_list = list.sort_by{|el| el.popularity}.uniq{|el| el.popularity}

Comments

0

Most of these answers didn't work for me, except for Glenn Mcdonalds (up until i posted this answer) I found an answer to my own question somewhere else like this

list = [2,1,4,4,4,1] #for example
count = Hash.new(0)
list.each {|element| count[element] += 1} #or some other parameter than element
list = list.uniq.sort {|x,y| count[y] <=> count[x]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.