3

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?

1
  • 1
    Welcome to Stack Overflow. Have you tried writing code? We'd prefer to correct what you've written rather than write new code for you. It's easier for you to correct something than to shoehorn in new code that is totally unrelated to any code surrounding it. Commented May 19, 2015 at 22:42

4 Answers 4

11

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]
Sign up to request clarification or add additional context in comments.

2 Comments

That will work but will get geometrically slower on larger arrays.
array.count iterates over all the elements in the array, just as select does, so for an array of 500K elements, this could be cripplingly slow, as it'd do 250 billion operations. A one-pass approach using group_by might be faster here.
5

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

Comments

2

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]

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.