选择数组中重复的数字序列?

时间:2013-09-09 19:48:46

标签: ruby

给定一组数字,如何选择阵列中重复次数最多的数字?

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

1 个答案:

答案 0 :(得分:2)

这里只是重复

arr = [4,3, 3, 2, 1, 3, 3, 3, 4, 4, 4, 4, 0, 0, 0, 1, 3, 4, 0]
arr.group_by{|e| e}.max_by{|k,v| v.size}.first
# => 4

arr = [4,3, 3, 2, 1, 3, 3, 3, 4, 4, 4, 4, 0, 0, 0, 1, 3, 4, 0]
arr.uniq.max_by{|e| arr.count(e)}
# => 4

另一个是连续重复

arr = [4,3, 3, 2, 1, 3, 3, 3, 4, 4, 4, 4, 0, 0, 0, 1, 3, 4, 0]
arr.chunk{|e| e}.max_by{|e| e.last.size}.first
# => 4

根据 @Tessi Benchmark report

require 'benchmark'
iterations = 10_000
arr = Array.new(1000) {(rand()*100).to_i}

def max_babai1(arr)
  arr.group_by{|e| e}.max_by{|k,v| v.size}.first
end

def max_babai2(arr)
  arr.uniq.max_by{|e| arr.count(e)}
end

Benchmark.bm do |bm|
  bm.report('babai1') do
    iterations.times do
      max_babai1 arr
    end
  end

  bm.report('babai2') do
    iterations.times do
      max_babai2 arr
    end
  end
end

<强>输出

ruby --version
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux]

ruby bench.rb         
       user     system      total        real
babai1  1.700000   0.000000   1.700000 (  1.707292)
babai2 29.630000   0.010000  29.640000 ( 29.769966)