Home > front end >  Ruby - Given an array of nested arrays, how to find the max only comparing the last value of each ne
Ruby - Given an array of nested arrays, how to find the max only comparing the last value of each ne

Time:08-09

Beginner trying to create a simple stock picker program. So far my program takes a flat array of integers representing stock prices (indices are days) and returns an array of nested arrays. Each nested array has three values [each consecutive buy day index, best sell day index, profit]. Like so:

stock_prices = [17,2,20,6,9,15,8,1,15,15]
best_days = [[0, 2, 3], [1, 2, 18], [2, 5, -5], [3, 5, 9], [4, 5, 6], [5, 8, 0], [6, 8, 7], [7, 8, 14], [8, 9, 0]]

I would like to find the max profit day, then return an array that contains the index values of the buy and sell days of that day. In this case it would be:

absolute_best = [1, 2]

How do I iterate through an array of nested arrays but only compare the final value of each nested array?

CodePudding user response:

To find the largest array element by a condition (here: the value of its 3rd element) you can use max_by in various ways.

Using array decomposition to extract the 3rd element:

best_days.max_by { |a, b, c| c }

# or

best_days.max_by { |_, _, c| c }

# or

best_days.max_by { |*, c| c }

Using the array as is and retrieve its last value:

best_days.max_by { |ary| ary.last }

# or

best_days.max_by(&:last)

All of the above return [1, 2, 18].

In addition to max_by there's also sort_by which can be used to sort the array by profit.

  • Related