Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby: how to find non-unique elements in array and print each with number of occurrences?

Tags:

arrays

ruby

I have

a = ["a", "d", "c", "b", "b", "c", "c"]

and need to print something like (sorted descending by number of occurrences):

c:3
b:2

I understand first part (finding NON-unique) is:

b = a.select{ |e| a.count(e) > 1 }
=> ["c", "b", "b", "c", "c"] 

or

puts b.select{|e, c| [e, a.count(e)] }.uniq

c
b

How to output each non-unique with number of occurrences sorted backwards?

like image 916
earlyadopter Avatar asked Mar 07 '13 23:03

earlyadopter


People also ask

How do you check if there are duplicates in an array Ruby?

select { array. count } is a nested loop, you're doing an O(n^2) complex algorithm for something which can be done in O(n). You're right, to solve this Skizit's question we can use in O(n); but in order to find out which elements are duplicated an O(n^2) algo is the only way I can think of so far.

How can you get the number of items contained in an array Ruby?

Ruby | Array count() operation Array#count() : count() is a Array class method which returns the number of elements in the array. It can also find the total number of a particular element in the array. Syntax: Array. count() Parameter: obj - specific element to found Return: removes all the nil values from the array.

What does .first do in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.


1 Answers

puts a.uniq.
       map { | e | [a.count(e), e] }.
       select { | c, _ | c > 1 }.
       sort.reverse.
       map { | c, e | "#{e}:#{c}" }
like image 94
undur_gongor Avatar answered Sep 19 '22 17:09

undur_gongor