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.

jbk
  • 1,911
  • 19
  • 36

1 Answers1

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]
spickermann
  • 100,941
  • 9
  • 101
  • 131
  • 1
    Ha ha, amazing, so simple when you know how!!!! Thanks @spickermann. – jbk Mar 07 '23 at 14:55
  • 1
    @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. – engineersmnky Mar 07 '23 at 16:35
  • 1
    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. – Cary Swoveland Mar 07 '23 at 21:43
  • 1
    @CarySwoveland it's a shame we can't use the [trailing comma parallel assignment syntax](https://stackoverflow.com/questions/75596144/trailing-comma-in-ruby-parameter-signature) with the splat syntax. – engineersmnky Mar 08 '23 at 01:41