Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I efficiently extract repeated elements in a Ruby array? [duplicate]

I have an array like [1,1,1,2,4,6,3,3] and I would like to get the list of repeated elements, in this case [1,3]. I wrote this:

my_array.select{|obj|my_array.count(obj)>1}.uniq

But it is tragically inefficient (o(n²)). Do you have a better idea? If possible concise.

Thanks

like image 321
MiniQuark Avatar asked Apr 24 '09 17:04

MiniQuark


People also ask

How do you find repeated elements in an array?

Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.

How do you remove duplicate values from an array in Ruby?

With the uniq method you can remove ALL the duplicate elements from an array. Let's see how it works! Where the number 1 is duplicated. Calling uniq on this array removes the extra ones & returns a NEW array with unique numbers.

How do I remove a repeated value from an array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.

What does the .each method do in Ruby?

The each() is an inbuilt method in Ruby iterates over every element in the range. Parameters: The function accepts a block which specifies the way in which the elements are iterated. Return Value: It returns every elements in the range.


1 Answers

Inspired by Ilya Haykinson's answer:

def repeated(array)
  counts = Hash.new(0)
  array.each{|val|counts[val]+=1}
  counts.reject{|val,count|count==1}.keys
end
like image 106
MiniQuark Avatar answered Sep 23 '22 06:09

MiniQuark