arr = [4, 9, 0, -3, 16, 7]
Is there any simple way to find the indicies of the lowest x elements? Something like this?
arr.min_index(4)
arr = [4, 9, 0, -3, 16, 7]
Is there any simple way to find the indicies of the lowest x elements? Something like this?
arr.min_index(4)
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]
Here's one simple way to do it:
class Array
def min_index(n)
each_with_index.sort.map(&:last).first(n)
end
end
>> arr = [4, 9, 0, -3, 16, 7]
>> arr.min_index(4)
#> [3, 2, 0, 5]
>> [4, 2, 2].min_by(2)
#> [1, 2]