How to Find a Min/Max with Ruby

How to find a min/max with Ruby

You can do

[5, 10].min

or

[4, 7].max

They come from the Enumerable module, so anything that includes Enumerable will have those methods available.

v2.4 introduces own Array#min and Array#max, which are way faster than Enumerable's methods because they skip calling #each.

@nicholasklick mentions another option, Enumerable#minmax, but this time returning an array of [min, max].

[4, 5, 7, 10].minmax
=> [4, 10]

How to get min/max value indices in a Ruby array

arr.each_index.min_by(x) { |i| arr[i] }

or

arr.each_with_index.min(x).map(&:last)

Demo:

> arr, x = [4, 9, 0, -3, 16, 7], 4
=> [[4, 9, 0, -3, 16, 7], 4]
> arr.each_index.min_by(x) { |i| arr[i] }
=> [3, 2, 0, 5]
> arr.each_with_index.min(x).map(&:last)
=> [3, 2, 0, 5]

How does ruby's .min and .max method work, and what is the time complexity when using those methods to find min or max value in an array?

The .min and .max operations in the each are being applied to arrays with only 2 elements, so each is an O(1) operation. Changing n, the number of elements in stock_prices, won't change the amount of time to find either the .min or .max in each iteration, they are independent of n. Consequently, the entire block is O(n).

Get min and max value from this array of hashes

By default when you sort an array sorts by the first element first.

You can reverse the array for the purposes of the sort.

channel_counts_for_history_graph.map(&:reverse).max[0]

Rails mulitple AR operations (min, max, avg.. ) on same query object

I think this should work:

PriceHistory.where(
'created_at >= ? AND cast(item_id as integer) = ?',
1.day.ago,
params['item_id']
).group(:day).select(
"SUM(price) AS sum_price",
"MAX(price) AS max_price",
"MIN(price) AS min_price",
"AVG(price) AS avg_price",
"day"
)

This will return you an array of records, each which has methods day, sum_price, max_price, min_price, and avg_price.

Note that the names of the SQL functions might be different based on your db

Using .minmax to return values only when min is in lower index position of an array

I would try:

array[0..array.index(array.max)].minmax

So just apply minmax to the elements between the first of the array and the index of the maximum.

To return the index values, just use map to iterate through the minmax array and get their indexes in a new array:

array         = [10, 12, 5, 3, 20, 1, 9]
min_max_array = array[0..array.index(array.max)].minmax
min_max_index = min_max_array.map{|v| array.index(v)}


Related Topics



Leave a reply



Submit