Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect duplicate values within an array in Ruby?

Tags:

arrays

ruby

Say I have an array that looks like:

a = [cat, dog, cat, mouse, rat, dog, cat]

How do I cycle through that, and do something with duplicates - e.g. say delete them?

In other words, if I did a.each do |i|, how do I evaluate a[0], against a[1], a[2], a[3]...and then when I find the one I want, say a[2] in this case has the first duplicate, I then push it to a stack or remove it or something.

I know how to evaluate keys, versus values...but how do I evaluate values against each other within the same array?

Thanks.

like image 733
marcamillion Avatar asked Mar 07 '12 10:03

marcamillion


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 do I check if an array contains duplicate numbers?

function checkIfArrayIsUnique(myArray) { for (var i = 0; i < myArray. length; i++) { for (var j = i+1; j < myArray. length; j++) { if (myArray[i] == myArray[j]) { return true; // means there are duplicate values } } } return false; // means there are no duplicate values. }

How do you find duplicate objects in an array?

Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.

How do you find the duplicate number on a given integer array in Ruby?

Ruby Array objects have a great method, select . In this case, you are interested in duplicates (objects which appear more than once in the array). The appropriate test is a. count(obj) > 1 .


1 Answers

You can create a hash to store number of times any element is repeated. Thus iterating over array just once.

h = Hash.new(0)
['a','b','b','c'].each{ |e| h[e] += 1 }

Should result

 {"a"=>1, "b"=>2, "c"=>1}
like image 145
ch4nd4n Avatar answered Nov 08 '22 15:11

ch4nd4n