arr
是字符串数组:
["hello", "world", "stack", "overflow", "hello", "again"]
一种简单又优雅的方法来检查是否arr
有重复项,如果有重复项,则返回其中一个(无论哪个)?
例子:
["A", "B", "C", "B", "A"] # => "A" or "B"
["A", "B", "C"] # => nil
arr
是字符串数组:
["hello", "world", "stack", "overflow", "hello", "again"]
一种简单又优雅的方法来检查是否arr
有重复项,如果有重复项,则返回其中一个(无论哪个)?
例子:
["A", "B", "C", "B", "A"] # => "A" or "B"
["A", "B", "C"] # => nil
Answers:
a = ["A", "B", "C", "B", "A"]
a.detect{ |e| a.count(e) > 1 }
我知道这不是一个很好的答案,但我喜欢。这是一个漂亮的班轮代码。除非您需要处理海量数据集,否则它工作得很好。
寻找更快的解决方案?干得好!
def find_one_using_hash_map(array)
map = {}
dup = nil
array.each do |v|
map[v] = (map[v] || 0 ) + 1
if map[v] > 1
dup = v
break
end
end
return dup
end
它是线性的O(n),但现在需要管理多行代码,需要测试用例等。
如果您需要更快的解决方案,请尝试使用C。
这是比较不同解决方案的要点:https : //gist.github.com/naveed-ahmad/8f0b926ffccf5fbd206a1cc58ce9743e
a.select {|e| a.count(e) > 1}.uniq
您可以通过几种方式来做到这一点,第一种选择是最快的:
ary = ["A", "B", "C", "B", "A"]
ary.group_by{ |e| e }.select { |k, v| v.size > 1 }.map(&:first)
ary.sort.chunk{ |e| e }.select { |e, chunk| chunk.size > 1 }.map(&:first)
和O(N ^ 2)选项(即效率较低):
ary.select{ |e| ary.count(e) > 1 }.uniq
group_by.select
ary.group_by(&:itself)
。:-)
只需找到第一个实例,其中对象的索引(从左侧开始计数)不等于对象的索引(从右侧开始计数)。
arr.detect {|e| arr.rindex(e) != arr.index(e) }
如果没有重复项,则返回值为零。
我认为,这也是到目前为止线程中发布的最快的解决方案,因为它不依赖于其他对象的创建,#index
并且#rindex
是在C语言中实现的。big-O运行时为N ^ 2,因此比Sergio的,但是由于“慢速”部分在C中运行,因此挂墙时间可能要快得多。
arr.find_all {|e| arr.rindex(e) != arr.index(e) }.uniq
arr.detect.with_index { |e, idx| idx != arr.rindex(e) }
。使用with_index
应该删除第一次index
搜索的必要性。
detect
只找到一个副本。find_all
将找到所有这些:
a = ["A", "B", "C", "B", "A"]
a.find_all { |e| a.count(e) > 1 }
count
数组中的每个元素都非常麻烦。(A计数散列,例如,是更有效的;例如,构建体h = {"A"=>2, "B"=>2, "C"=> 1 }
然后h.select { |k,v| v > 1 }.keys #=> ["A", "B"]
。
这是找到重复项的另外两种方法。
使用一套
require 'set'
def find_a_dup_using_set(arr)
s = Set.new
arr.find { |e| !s.add?(e) }
end
find_a_dup_using_set arr
#=> "hello"
用于select
代替find
返回所有重复项的数组。
用 Array#difference
class Array
def difference(other)
h = other.each_with_object(Hash.new(0)) { |e,h| h[e] += 1 }
reject { |e| h[e] > 0 && h[e] -= 1 }
end
end
def find_a_dup_using_difference(arr)
arr.difference(arr.uniq).first
end
find_a_dup_using_difference arr
#=> "hello"
删除.first
以返回所有重复项的数组。
nil
如果没有重复,则这两种方法都将返回。
我建议将Array#difference
其添加到Ruby核心中。更多信息可在我的答案在这里。
基准测试
让我们比较建议的方法。首先,我们需要一个数组进行测试:
CAPS = ('AAA'..'ZZZ').to_a.first(10_000)
def test_array(nelements, ndups)
arr = CAPS[0, nelements-ndups]
arr = arr.concat(arr[0,ndups]).shuffle
end
以及为不同测试阵列运行基准测试的方法:
require 'fruity'
def benchmark(nelements, ndups)
arr = test_array nelements, ndups
puts "\n#{ndups} duplicates\n"
compare(
Naveed: -> {arr.detect{|e| arr.count(e) > 1}},
Sergio: -> {(arr.inject(Hash.new(0)) {|h,e| h[e] += 1; h}.find {|k,v| v > 1} ||
[nil]).first },
Ryan: -> {(arr.group_by{|e| e}.find {|k,v| v.size > 1} ||
[nil]).first},
Chris: -> {arr.detect {|e| arr.rindex(e) != arr.index(e)} },
Cary_set: -> {find_a_dup_using_set(arr)},
Cary_diff: -> {find_a_dup_using_difference(arr)}
)
end
我没有包含@JjP的答案,因为仅返回一个重复项,并且修改他/她的答案以使其与@Naveed的早期答案相同。我也没有包括@Marin的答案,该答案发布在@Naveed的答案之前,返回的是所有重复项,而不仅仅是一个(略有一点,但没有必要对两者进行评估,因为当返回一个重复项时它们是相同的)。
我还修改了其他答案,这些答案返回所有重复项,仅返回找到的第一个重复项,但这对性能基本上没有影响,因为它们在选择一个重复项之前计算了所有重复项。
每个基准测试的结果从最快到最慢列出:
首先假设数组包含100个元素:
benchmark(100, 0)
0 duplicates
Running each test 64 times. Test will take about 2 seconds.
Cary_set is similar to Cary_diff
Cary_diff is similar to Ryan
Ryan is similar to Sergio
Sergio is faster than Chris by 4x ± 1.0
Chris is faster than Naveed by 2x ± 1.0
benchmark(100, 1)
1 duplicates
Running each test 128 times. Test will take about 2 seconds.
Cary_set is similar to Cary_diff
Cary_diff is faster than Ryan by 2x ± 1.0
Ryan is similar to Sergio
Sergio is faster than Chris by 2x ± 1.0
Chris is faster than Naveed by 2x ± 1.0
benchmark(100, 10)
10 duplicates
Running each test 1024 times. Test will take about 3 seconds.
Chris is faster than Naveed by 2x ± 1.0
Naveed is faster than Cary_diff by 2x ± 1.0 (results differ: AAC vs AAF)
Cary_diff is similar to Cary_set
Cary_set is faster than Sergio by 3x ± 1.0 (results differ: AAF vs AAC)
Sergio is similar to Ryan
现在考虑一个具有10,000个元素的数组:
benchmark(10000, 0)
0 duplicates
Running each test once. Test will take about 4 minutes.
Ryan is similar to Sergio
Sergio is similar to Cary_set
Cary_set is similar to Cary_diff
Cary_diff is faster than Chris by 400x ± 100.0
Chris is faster than Naveed by 3x ± 0.1
benchmark(10000, 1)
1 duplicates
Running each test once. Test will take about 1 second.
Cary_set is similar to Cary_diff
Cary_diff is similar to Sergio
Sergio is similar to Ryan
Ryan is faster than Chris by 2x ± 1.0
Chris is faster than Naveed by 2x ± 1.0
benchmark(10000, 10)
10 duplicates
Running each test once. Test will take about 11 seconds.
Cary_set is similar to Cary_diff
Cary_diff is faster than Sergio by 3x ± 1.0 (results differ: AAE vs AAA)
Sergio is similar to Ryan
Ryan is faster than Chris by 20x ± 10.0
Chris is faster than Naveed by 3x ± 1.0
benchmark(10000, 100)
100 duplicates
Cary_set is similar to Cary_diff
Cary_diff is faster than Sergio by 11x ± 10.0 (results differ: ADG vs ACL)
Sergio is similar to Ryan
Ryan is similar to Chris
Chris is faster than Naveed by 3x ± 1.0
请注意,find_a_dup_using_difference(arr)
如果Array#difference
用C实现,效率会大大提高,如果将其添加到Ruby核心中,情况将会更有效。
结论
许多答案都是合理的,但使用Set无疑是最佳选择。在中等难度的情况下,它是最快的;在最困难的情况下,它是最快的,并且仅在计算上不重要的情况下-当您的选择仍然无关紧要时-可以被击败。
您可能会选择克里斯的解决方案的一种非常特殊的情况是,如果您想使用该方法分别对数千个小型阵列进行重复数据消除,并希望找到通常少于10个项目的重复数据,则速度会更快一些。因为它避免了创建集合的少量额外开销。
las,大多数答案是O(n^2)
。
这是一个O(n)
解决方案,
a = %w{the quick brown fox jumps over the lazy dog}
h = Hash.new(0)
a.find { |each| (h[each] += 1) == 2 } # => 'the"
这有什么复杂性?
O(n)
比赛并在第一个比赛中休息O(n)
内存,但仅占用少量内存现在,根据阵列中重复项的频率,这些运行时实际上可能会变得更好。例如,如果O(n)
从一组k << n
不同的元素中采样了大小数组,则运行时和空间的复杂度都变为O(k)
,但是原始海报更可能验证输入并希望确保没有重复。在这种情况下,O(n)
由于我们希望元素对大多数输入没有重复,因此运行时和内存都非常复杂。
Ruby Array对象有一个很棒的方法select
。
select {|item| block } → new_ary
select → an_enumerator
第一种形式是您在这里感兴趣的。它允许您选择通过测试的对象。
Ruby Array对象还有另一种方法count
。
count → int
count(obj) → int
count { |item| block } → int
在这种情况下,您对重复项(对象在数组中出现多次)感兴趣。适当的测试是a.count(obj) > 1
。
如果a = ["A", "B", "C", "B", "A"]
,那么
a.select{|item| a.count(item) > 1}.uniq
=> ["A", "B"]
您声明只需要一个对象。所以选一个。
["A", "B", "B", "A"]
.uniq
数组。
count
为数组的每个元素调用,这是浪费和不必要的。请参阅我对JjP答案的评论。
find_all()返回一个array
包含的所有元素enum
为哪些block
不是false
。
获取duplicate
元素
>> arr = ["A", "B", "C", "B", "A"]
>> arr.find_all { |x| arr.count(x) > 1 }
=> ["A", "B", "B", "A"]
或重复uniq
元素
>> arr.find_all { |x| arr.count(x) > 1 }.uniq
=> ["A", "B"]
我知道这个线程是专门针对Ruby的,但是我登陆这里寻找如何在Ruby on Rails中使用ActiveRecord来实现这一点,并认为我也将分享我的解决方案。
class ActiveRecordClass < ActiveRecord::Base
#has two columns, a primary key (id) and an email_address (string)
end
ActiveRecordClass.group(:email_address).having("count(*) > 1").count.keys
上面的代码返回在此示例的数据库表中重复的所有电子邮件地址的数组(在Rails中为“ active_record_classes”)。
a = ["A", "B", "C", "B", "A"]
a.each_with_object(Hash.new(0)) {|i,hash| hash[i] += 1}.select{|_, count| count > 1}.keys
这是一个O(n)
过程。
或者,您可以执行以下任一行。也是O(n)但只有一次迭代
a.each_with_object(Hash.new(0).merge dup: []){|x,h| h[:dup] << x if (h[x] += 1) == 2}[:dup]
a.inject(Hash.new(0).merge dup: []){|h,x| h[:dup] << x if (h[x] += 1) == 2;h}[:dup]
这是我对大量数据的看法-例如用于查找重复部分的旧式dBase表
# Assuming ps is an array of 20000 part numbers & we want to find duplicates
# actually had to it recently.
# having a result hash with part number and number of times part is
# duplicated is much more convenient in the real world application
# Takes about 6 seconds to run on my data set
# - not too bad for an export script handling 20000 parts
h = {};
# or for readability
h = {} # result hash
ps.select{ |e|
ct = ps.count(e)
h[e] = ct if ct > 1
}; nil # so that the huge result of select doesn't print in the console
each_with_object
是你的朋友!
input = [:bla,:blubb,:bleh,:bla,:bleh,:bla,:blubb,:brrr]
# to get the counts of the elements in the array:
> input.each_with_object({}){|x,h| h[x] ||= 0; h[x] += 1}
=> {:bla=>3, :blubb=>2, :bleh=>2, :brrr=>1}
# to get only the counts of the non-unique elements in the array:
> input.each_with_object({}){|x,h| h[x] ||= 0; h[x] += 1}.reject{|k,v| v < 2}
=> {:bla=>3, :blubb=>2, :bleh=>2}
此代码将返回重复值的列表。哈希键用作检查已看到哪些值的有效方法。根据是否看到值,将原始数组ary
划分为2个数组:第一个包含唯一值,第二个包含重复值。
ary = ["hello", "world", "stack", "overflow", "hello", "again"]
hash={}
arr.partition { |v| hash.has_key?(v) ? false : hash[v]=0 }.last.uniq
=> ["hello"]
您可以将其进一步缩短为以下形式(尽管以稍微复杂一些的语法为代价):
hash={}
arr.partition { |v| !hash.has_key?(v) && hash[v]=0 }.last.uniq
a = ["A", "B", "C", "B", "A"]
b = a.select {|e| a.count(e) > 1}.uniq
c = a - b
d = b + c
结果
d
=> ["A", "B", "C"]
如果要比较两个不同的数组(而不是将其与自身比较),一种非常快速的方法是使用Ruby的Array类&
提供的相交运算符。
# Given
a = ['a', 'b', 'c', 'd']
b = ['e', 'f', 'c', 'd']
# Then this...
a & b # => ['c', 'd']
我需要找出有多少重复项以及它们是什么,因此我编写了一个功能,该功能是基于Naveed先前发布的内容构建的:
def print_duplicates(array)
puts "Array count: #{array.count}"
map = {}
total_dups = 0
array.each do |v|
map[v] = (map[v] || 0 ) + 1
end
map.each do |k, v|
if v != 1
puts "#{k} appears #{v} times"
total_dups += 1
end
end
puts "Total items that are duplicated: #{total_dups}"
end
让我们在代码实现中进行演示
def duplication given_array
seen_objects = []
duplication_objects = []
given_array.each do |element|
duplication_objects << element if seen_objects.include?(element)
seen_objects << element
end
duplication_objects
end
现在调用复制方法并输出返回结果-
dup_elements = duplication [1,2,3,4,4,5,6,6]
puts dup_elements.inspect
arr == arr.uniq
这将是一种简单而优雅的方法来检查是否arr
有重复项,但是,它不提供重复项。