2

I have this nested array:

[[1, 2, 3],                                                                   
 [1, 3, 6],                                                                   
 [1, 4, 12],                                                                  
 [1, 5, 5],                                                                   
 [1, 2, 3],                                                                   
 [1, 8, 7],                                                                   
 [2, 3, 3],                                      
 [2, 4, 9],                                      
 [2, 5, 2],                                      
 [2, 8, 4],                                      
 [3, 4, 6],                                      
 [3, 8, 1],                                      
 [5, 8, 2],                                      
 [2, 8, 4],                                      
 [7, 8, 9]]

and I am trying to find a succinct but readable way of:

  1. comparing and finding the maximum value from those values in index position[2] (i.e. 3rd element in each nested array) within each of the nested arrays.
  2. Returning the neighbouring values at index[0] and [1] from the same nested array containing the maximum value from point 1.

I've unsuccessfully played around with various methods such as #max, #max_by, #group_by, #with_index but I'm now at the stage where I could just do with some enlightenment from a more capable brain and programmer then me.

0

1 Answer 1

6

Finding the nested array with the max value on the last element:

input = [[1, 2, 3], [1, 3, 6], [1, 4, 12], [1, 5, 5], [1, 2, 3], [1, 8, 7], [2, 3, 3], [2, 4, 9], [2, 5, 2], [2, 8, 4], [3, 4, 6], [3, 8, 1], [5, 8, 2], [2, 8, 4], [7, 8, 9]]
input.max_by(&:last)
#=> [1, 4, 12]

And to only return its first two values:

input.max_by(&:last).take(2)
#=> [1, 4]
Sign up to request clarification or add additional context in comments.

4 Comments

Ha ha, amazing, so simple when you know how!!!! Thanks @spickermann.
@jbk please note max_by will return the first object in the event of a tie, meaning if input << [10,11,12] the result of this post would be the same.
A slight variant is input.max_by(&:last).values_at(0, 1), which is perhaps slightly more descriptive. Alternatively, *v01, _v2 = input.max_by(&:last), where the desired result is v01 #=> [1, 4] and, while not needed (as signalled to the reader by the variable name beginning with an underscore), having the maximum value _v2 #=> 12 might be helpful in testing.
@CarySwoveland it's a shame we can't use the trailing comma parallel assignment syntax with the splat syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.