1

Given an array of numbers, how can I select the number in the array that's has been repeated the most times?

arr = [4,3, 3, 2, 1, 3, 3, 3, 4, 4, 4, 4, 0, 0, 0, 1, 3, 4, 0]
4
  • 3
    Do you mean repeated consecutively, or just repeated? Commented Sep 9, 2013 at 19:49
  • @NicholasAlek Do you mean repeated in a row? What number wins in this case: [1, 1, 2, 2, 2, 1, 1] 2 or 1? Commented Sep 9, 2013 at 19:55
  • I see, just repeated. It really doesn't matter in which order numbers come. Commented Sep 9, 2013 at 19:58
  • 2
    Have you attempted any solution yourself? Commented Sep 9, 2013 at 19:59

1 Answer 1

2

Here it is for just repeated:

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

or

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

Another is for repeated consecutively :

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

As per the @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

Output

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)
Sign up to request clarification or add additional context in comments.

15 Comments

That's the one!!! Thanks. Can you walk me through your code?
@NicholasAlek which one is your one? First one(repeated) or last one(repeated consecutively) ? :)
Ahhh, doesn't matter which order, first or last.
for the repeated one you can use chunk if you sort first: arr.sort.chunk{|v|v}.max_by{|val,a| a.size}.first. Although neither implementation handles ties.
@firien why sort is needed ? You probably didn't catch the difference between the 2 codes.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.