Find a Duplicate in an array Ruby -


i trying find duplicate values in array of strings between 1 1000000.

however, code have, output entries doubled.

so instance, if have [1,2,3,4,3,4], gives me output of 3 4 3 4 instead of 3 4.

here code:

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

also, every time test code, have define array array = [1,2,3,4,5,3,5]. puts works not print when use array [gets].

can me how fix these 2 problems?

array#difference comes rescue yet again. (i confess @user123's answer more straightforward, unless pretend array#difference built-in method. array#difference more efficient of two, avoids repeated invocations of count.) see answer here description of method , links use. in nutshell, differs array#- illustrated in following example:

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

one day i'd see built-in.

for present problem, if:

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

the duplicate elements given by:

arr.difference(arr.uniq).uniq   #=> [3, 4] 

Comments