Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Sum without highest and lowest number in an array

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.84k
    Comment on it

    Description:

    Sum all the numbers of the array except the highest and the lowest element.

    Example: { 6, 2, 1, 8, 10 } => 16

    If array is empty or null, or if only 1 Element exists, return 0.

     

    Test Cases:

    Test.describe("Basic tests") do
    Test.it("nil or Empty") do
    Test.assert_equals(sum_array(nil), 0)
    Test.assert_equals(sum_array([]), 0)
    end
    Test.it("Only one Element") do
    Test.assert_equals(sum_array([3]), 0)
    Test.assert_equals(sum_array([-3]), 0)
    end
    Test.it("Only two Element") do
    Test.assert_equals(sum_array([ 3, 5]), 0)
    Test.assert_equals(sum_array([-3, -5]), 0)
    end
    Test.it("Real Tests") do
    Test.assert_equals(sum_array([6, 2, 1, 8, 10]), 16)
    Test.assert_equals(sum_array([6, 0, 1, 10, 10]), 17)
    Test.assert_equals(sum_array([-6, -20, -1, -10, -12]), -28)
    Test.assert_equals(sum_array([-6, 20, -1, 10, -12]), 3)
    end
    end

     

     

    Solutions:

     

    def sum_array(a)
      if a == nil || a == [] || a.length <=1 then return 0 end
      a = a.sort()
      a.inject(0){|t,x| t + x } - a[0] - a[-1]
    end

    OR

    def sum_array(arr) (arr.class!=Array or arr.length<3) ? 0 : arr.reduce([0,9999999999999,-9999999999999]){|a,b| [a[0]+b,a[1]>b ? b : a[1],a[2]<b ? b : a[2]]}.reduce{|a,b| a-b} end

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: