如何在 Ruby 数组中获取 min/max 值索引
How to get min/max value indices in a Ruby array
arr = [4, 9, 0, -3, 16, 7]
有什么简单的方法可以找到最低 x 元素的索引吗?是这样的吗?
arr.min_index(4)
这是一种简单的方法:
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]
arr.each_index.min_by(x) { |i| arr[i] }
或
arr.each_with_index.min(x).map(&:last)
演示:
> 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]
arr = [4, 9, 0, -3, 16, 7]
有什么简单的方法可以找到最低 x 元素的索引吗?是这样的吗?
arr.min_index(4)
这是一种简单的方法:
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]
arr.each_index.min_by(x) { |i| arr[i] }
或
arr.each_with_index.min(x).map(&:last)
演示:
> 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]