Topic: how to sum the 2 largest elements in an array

I have a method, in which I have created an array of numbers, I want to sum the two largest elements of the array, which I thought worked fine until I moved the numbers around.

def max_2_sums
  array = [3, 4, 5]
  array.sort!
  num_1 = array.max
  num_2 = array.length-1
    max_2_sum = 0
    array.each do |item|
      max_2_sum = num_1 + num_2
    end
    puts max_2_sum
  end

what have I done wrong?

Re: how to sum the 2 largest elements in an array

Try this

def max_2_sums
  array = [1,9,11,2,4,8,32] #The sum of the highest 2values should be 43
  array.sort{ |x, y| y <=> x }
  sum = array[0] + array[1]  
end
What you want and what you need are too often not the same thing!
When your head is hurting from trying to solve a problem, stop standing on it. When you are the right way up you will see the problem differently and you just might find the solution.
(Quote by me 15th July 2009)

Re: how to sum the 2 largest elements in an array

[1, 3, 2, 5, 3, 6, 34, 4, 2].sort.last(2).reduce(&:+)

and if you need a function

def max_2_sums arr
    arr.sort.last(2).reduce(&:+)
end

max_2_sum [1, 3, 2, 5, 3, 6, 34, 4, 2]

or even

class Array
 def max_2_sums
   self.sort.last(2).reduce(&:+)
end
end

[1,3,54,2,3,5,6].max_2_sums

Last edited by kham (2013-03-20 08:11:34)

Re: how to sum the 2 largest elements in an array

Someday I will truly understand bubble sorts (jamesaw's comment) but didn't get em in javascript, still don't get it in ruby - just know they work - which will be important when I'm doing statistics and sorting of averages and such smile

Re: how to sum the 2 largest elements in an array

I didn't know about reduce, but I knew about inject:

a.sort.last(2).inject { |sum, i| sum + i }

I tried my very first benchmark on this, too, and happily claim my method to be faster on my machine! smile

#!/usr/bin/env ruby
require 'benchmark'

Benchmark.bm do |b|
  a = [1, 3, 2, 5, 3, 6, 34, 4, 2].sort.last(2)
  
  b.report("inject") do
    1000000.times { a.inject { |sum, i| sum + i } }
  end

  b.report("reduce") do
    1000000.times { a.reduce(&:+) }
  end
end

#       user     system      total        real
# inject  0.800000   0.000000   0.800000 (  0.813485)
# reduce  1.000000   0.000000   1.000000 (  1.015254)