查找数组的Ruby一个重复 [英] Find a Duplicate in an array Ruby

查看:212
本文介绍了查找数组的Ruby一个重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到1之间的一个字符串数组重复值为1000000。

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

不过,与code我有,我得到的输出作为增加一倍的所有条目。

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

因此​​,举例来说,如果我有 [1,2,3,4,3,4] ,它给我的3 4 3 4,而不是3的输出4。

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.

下面是我的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

另外,我每次测试我的code的时候,我一定要定义数组为阵列= [1,2,3,4,5,3,5] 。在看跌的作品,但是当我使用数组未打印[变得]

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?

推荐答案

阵列#区别就派上用场了,再。 (我承认,@ user123的回答是更直接的,除非你pretend的阵列#区别已经是一个内置的方法。阵列#区别可能是更有效的两个人,因为它避免了计数的重复调用)查看我的回答的here 的方法并链接到其使用的说明。
阵列不同# >中所说明下面的例子:

Array#difference comes to the rescue yet again. (I confess that @user123's answer is more straightforward, unless you pretend that Array#difference is already a built-in method. 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]

有一天,我想看到​​它作为一个内置。

One day I'd like to see it as a built-in.

对于present问题,如果:

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]

这篇关于查找数组的Ruby一个重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆