Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a Duplicate in an array Ruby

Tags:

arrays

ruby

I am trying to find the duplicate values in an array of strings between 1 to 1000000.

However, with the code I have, I get the output as all the entries that are doubled.

So for instance, if I have [1,2,3,4,3,4], it gives me the output of 3 4 3 4 instead of 3 4.

Here is my code:

array = [gets]

if array.uniq.length == array.length
  puts "array does not contain duplicates"
else
  puts "array does contain duplicates"
  print array.select{ |x| array.count(x) > 1}
end

Also, every time I test my code, I have to define the array as array = [1,2,3,4,5,3,5]. The puts works but it does not print when I use array [gets].

Can someone help me how to fix these two problems?

like image 489
Shaili Parikh Avatar asked Dec 04 '25 23:12

Shaili Parikh


2 Answers

How I wish we had a built-in method Array#difference:

class Array
  def difference(other)
    h = other.tally
    reject { |e| h[e] > 0 && h[e] -= 1 }
  end
end

though @user123's answer is more straightforward. (Array#difference is probably the more efficient of the two, as it avoids the repeated invocations of count.) See my answer here for a description of the method and links to its use.

In a nutshell, it differs from Array#- as illustrated in the following example:

a = [1,2,3,4,3,2,4,2]
b = [2,3,4,4,4]

a - b          #=> [1]
a.difference b #=> [1, 3, 2, 2]

For the present problem, if:

arr = [1,2,3,4,3,4]

the duplicate elements are given by:

arr.difference(arr.uniq).uniq
  #=> [3, 4]
like image 58
Cary Swoveland Avatar answered Dec 06 '25 12:12

Cary Swoveland


For your first problem, you need to uniq function like

array.select{ |x| array.count(x) > 1}.uniq

For your second problem, when you receive a value using array = [gets] it would receive your entire sequence of array numbers as a single string, so everything would be stored in a[0] like ["1, 2 3 4\n"].

like image 41
RAJ Avatar answered Dec 06 '25 13:12

RAJ