Ruby:如何找到最小数组元素的索引?

发布于 2024-10-16 19:03:42 字数 187 浏览 8 评论 0原文

有什么办法可以重写得更优雅吗?我认为这是一段糟糕的代码,应该重构。

>> a = [2, 4, 10, 1, 13]
=> [2, 4, 10, 1, 13]
>> index_of_minimal_value_in_array = a.index(a.min)
=> 3

Is there any way to rewrite this more elegant? I think, that it's a bad piece of code and should be refactored.

>> a = [2, 4, 10, 1, 13]
=> [2, 4, 10, 1, 13]
>> index_of_minimal_value_in_array = a.index(a.min)
=> 3

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

雨落□心尘 2024-10-23 19:03:43

我相信这只会遍历数组一次并且仍然很容易阅读:

numbers = [20, 30, 40, 50, 10]           # => [20, 30, 40, 50, 10]
elem, idx = numbers.each_with_index.min  # => [10, 4]

I believe this will traverse the array only once and is still easy to read:

numbers = [20, 30, 40, 50, 10]           # => [20, 30, 40, 50, 10]
elem, idx = numbers.each_with_index.min  # => [10, 4]
绮烟 2024-10-23 19:03:43

这只会遍历数组一次,而 ary.index(ary.min) 会遍历数组两次:

ary.each_with_index.inject(0){ |minidx, (v,i)| v < a[minidx] ? i : minidx }

This traverses the array only once whereas ary.index(ary.min) would traverse it twice:

ary.each_with_index.inject(0){ |minidx, (v,i)| v < a[minidx] ? i : minidx }
离线来电— 2024-10-23 19:03:43

阅读其他情况(找到所有且仅最后一个最小元素)会很有趣。

ary = [1, 2, 1]

# find all matching elements' indexes
ary.each.with_index.find_all{ |a,i| a == ary.min }.map{ |a,b| b } # => [0, 2]
ary.each.with_index.map{ |a, i| (a == ary.min) ? i : nil }.compact # => [0, 2]

# find last matching element's index
ary.rindex(ary.min) # => 2

It would be interesting to read about other situations (finding all and only last minimal element).

ary = [1, 2, 1]

# find all matching elements' indexes
ary.each.with_index.find_all{ |a,i| a == ary.min }.map{ |a,b| b } # => [0, 2]
ary.each.with_index.map{ |a, i| (a == ary.min) ? i : nil }.compact # => [0, 2]

# find last matching element's index
ary.rindex(ary.min) # => 2
陪你搞怪i 2024-10-23 19:03:43

我实际上喜欢 @andersonvom 的答案,它只需要循环数组一次,仍然可以获得索引。

如果您不想使用ary.each_with_index.min,您可以执行以下操作:

ary = [2,3,4,5,1]                                             # => [2,3,4,5,1]
_, index_of_minimal_value_in_array = ary.each_with_index.min  # => [1, 4]
index_of_minimal_value_in_array                               # => 4

I actually like @andersonvom 's answer, it only need to loop the array once and still get the index.

And in case you don't want to use ary.each_with_index.min, here is what you can do:

ary = [2,3,4,5,1]                                             # => [2,3,4,5,1]
_, index_of_minimal_value_in_array = ary.each_with_index.min  # => [1, 4]
index_of_minimal_value_in_array                               # => 4
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文