Joey Hilton
Joey Hilton

Reputation: 81

Ruby - Find duplicates in an array

I am trying to write a method in Ruby that takes an array of size N and finds duplicates in the array and lists the duplicate.

I'm having trouble creating an array with a range of 0..N-2.

It tells me N is an uninitialized constant. How do I create such an array?

Upvotes: 3

Views: 9642

Answers (4)

Dami Ajayi
Dami Ajayi

Reputation: 19

I just wrote this, it works and I would like feedback so I'm sharing here.

def duplicate_array(arr)
  duplicates = []
  while arr.size != 1
    pivot = arr.shift
    arr.each do |element|
      if element.eql?(pivot)
        next if duplicates.include?(element)
        duplicates << element
      end
    end
  end
  duplicates
end

Upvotes: 0

Rohan Pujari
Rohan Pujari

Reputation: 838

You can write following code

def duplicate_value(array)
  array.select{|v| array.count(v) > 1}.uniq
end

duplicate_value([1, 2, 1, 3, 3])
=> [1, 3]

Upvotes: 2

tadman
tadman

Reputation: 211590

You can always use a simple counter hash:

def duplicate_count(array)
  array.each_with_object(Hash.new(0)) do |value, hash|
    # Keep a count of all the unique values encountered
    hash[value] += 1
  end.count do |(value,count)|
    # Compute how many have a count > 1
    count > 1
  end
end

duplicate_count([1,2,3,4])
# => 0

duplicate_count([1,2,2,3,4,4,2])
# => 2

If you'd prefer to return the duplicated values:

def duplicate_count(array)
  array.each_with_object(Hash.new(0)) do |value, hash|
    # Keep a count of all the unique values encountered
    hash[value] += 1
  end.each_with_object([ ]) do |(value,count), result|
    # Collect those with count > 1 into a result array.
    if (count > 1)
      result << value
    end
  end
end

Upvotes: 5

Richard Hamilton
Richard Hamilton

Reputation: 26444

Here's one option

def list_duplicates(array)
  duplicates = array.select { |e| array.count(e) > 1 }
  duplicates.uniq
end

I tested it out here

 list_duplicates([1,1,4,5,6,6,9]
 => [1,6]

Upvotes: 11

Related Questions