HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Sums of some array elements

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arraysomeelementssums

Problem

I'm doing an archived MOOC at the moment which introduces Ruby programming.
There are some assingments, yet no solutions and since the MOOC is over no one will correct those (+ the forum is down)

I'm totally new to Ruby (background in Java) and asking for some hints on my solution to the following task (my solution under the task):


Define a method sum which takes an array of integers as an argument and returns the sum of its elements. For an empty array it should return zero.

def sum(array)
  array[0] = array.pop + array[0];
  sum(array) until array.length == 1
  array.first
end



Define a method max_2_sum which takes an array of integers as an argument and returns the sum of its two largest elements. For an empty array it should return zero. For an array with just one element, it should return that element.

def max_2_sum(a)
  case a.length
    when 0
      return 0
    when 1
      return a.first
    else
      return (a.sort!.pop)+(a.sort!.pop)
  end
end


I think this is pretty verbose, yet I do not know how to solve that better


Define a method sum_to_n? which takes an array of integers and an additional integer, n, as arguments and returns true if any two distinct elements in the array of integers sum to n. An empty array or single element array should both return false.

def sum_to_n?(array, val)
  cartesian = array.product(array).select! { |c| c[0]+c[1] == val }
  not cartesian.empty?
end


I like this :)

Solution

Ruby can be an extremely concise language, where your programs are almost already written for you:

def sum(array)
    array.inject(0, :+)
end


Where the docs say:

inject { |memo, obj| block } → obj

Combines all elements of enum by applying a binary operation,
specified by a block or a symbol that names a method or operator.

In fact reading the docs can go a long way in shortening your programs.

Reading the docs for Array tells us that sorting is built-in and last (the twin of first) are too, also, we just wrote a handy sum function.

def max_2_sum(array)
    sum(array.sort.last(2))
end


This is slower than needed, that is O N log N instead of O N but it may be optimized iff it becomes a performance bottleneck (improbable).

Your last function is indeed nice, but the assignment was not necessary and you did not use the handy built-in any?

def sum_to_n?(array, val)
    array.product(array).any? {|couple| sum(couple) == val}
end

Code Snippets

def sum(array)
    array.inject(0, :+)
end
def max_2_sum(array)
    sum(array.sort.last(2))
end
def sum_to_n?(array, val)
    array.product(array).any? {|couple| sum(couple) == val}
end

Context

StackExchange Code Review Q#91270, answer score: 8

Revisions (0)

No revisions yet.