Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check an array for duplicates? [duplicate]

Tags:

arrays

ruby

I've got an array A. I'd like to check if it contains duplicate values. How would I do so?

like image 888
Skizit Avatar asked Dec 04 '10 01:12

Skizit


People also ask

How do you check if there are duplicates in array?

To check if an array contains duplicates:Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.

How do you find duplicates in an array if there is more than one duplicate?

Simple Approach: The idea is to use nested loop and for each element check if the element is present in the array more than once or not. If present, then store it in a Hash-map.

How do you check if there is a duplicate in an array Java?

One more way to detect duplication in the java array is adding every element of the array into HashSet which is a Set implementation. Since the add(Object obj) method of Set returns false if Set already contains an element to be added, it can be used to find out if the array contains duplicates in Java or not.


2 Answers

Just call uniq on it (which returns a new array without duplicates) and see whether the uniqed array has less elements than the original:

if a.uniq.length == a.length   puts "a does not contain duplicates" else   puts "a does contain duplicates" end 

Note that the objects in the array need to respond to hash and eql? in a meaningful for uniq to work properly.

like image 139
sepp2k Avatar answered Sep 28 '22 20:09

sepp2k


In order to find the duplicated elements, I use this approach (with Ruby 1.9.3):

array = [1, 2, 1, 3, 5, 4, 5, 5] => [1, 2, 1, 3, 5, 4, 5, 5] dup = array.select{|element| array.count(element) > 1 } => [1, 1, 5, 5, 5] dup.uniq => [1, 5] 
like image 45
jmonteiro Avatar answered Sep 28 '22 19:09

jmonteiro