给定一个数组,我怎样才能找到符合给定条件的所有元素索引?
例如,如果我有:
arr = ['x', 'o', 'x', '.', '.', 'o', 'x']
要找到项目为x
的所有索引,我可以这样做:
arr.each_with_index.map { |a, i| a == 'x' ? i : nil }.compact # => [0, 2, 6]
或
(0..arr.size-1).select { |i| arr[i] == 'x' } # => [0, 2, 6]
有没有更好的方法来实现这一目标?
答案 0 :(得分:85)
Ruby 1.9:
arr = ['x', 'o', 'x', '.', '.', 'o', 'x']
p arr.each_index.select{|i| arr[i] == 'x'} # =>[0, 2, 6]
答案 1 :(得分:24)
另一种方式:
arr.size.times.select {|i| arr[i] == 'x'} # => [0, 2, 6]
编辑:
不确定是否需要这样做,但这里是。
基准:
arr = 10000000.times.map{rand(1000)};
Benchmark.measure{arr.each_with_index.map { |a, i| a == 50 ? i : nil }.compact}
2.090000 0.120000 2.210000 ( 2.205431)
Benchmark.measure{(0..arr.size-1).select { |i| arr[i] == 50 }}
1.600000 0.000000 1.600000 ( 1.604543)
Benchmark.measure{arr.map.with_index {|a, i| a == 50 ? i : nil}.compact}
1.810000 0.020000 1.830000 ( 1.829151)
Benchmark.measure{arr.each_index.select{|i| arr[i] == 50}}
1.590000 0.000000 1.590000 ( 1.584074)
Benchmark.measure{arr.size.times.select {|i| arr[i] == 50}}
1.570000 0.000000 1.570000 ( 1.574474)
答案 2 :(得分:12)
比each_with_index.map
行略有改善
arr.map.with_index {|a, i| a == 'x' ? i : nil}.compact # => [0, 2, 6]
答案 3 :(得分:7)
这种方法有点长,但速度加倍
class Array
def find_each_index find
found, index, q = -1, -1, []
while found
found = self[index+1..-1].index(find)
if found
index = index + found + 1
q << index
end
end
q
end
end
arr = ['x', 'o', 'x', '.', '.', 'o', 'x']
p arr.find_each_index 'x'
# [0, 2, 6]
这里AGS的基准与这个解决方案相比
arr = 10000000.times.map{rand(1000)};
puts Benchmark.measure{arr.each_with_index.map { |a, i| a == 50 ? i : nil }.compact}
puts Benchmark.measure{(0..arr.size-1).select { |i| arr[i] == 50 }}
puts Benchmark.measure{arr.map.with_index {|a, i| a == 50 ? i : nil}.compact}
puts Benchmark.measure{arr.each_index.select{|i| arr[i] == 50}}
puts Benchmark.measure{arr.size.times.select {|i| arr[i] == 50}}
puts Benchmark.measure{arr.find_each_index 50}
# 1.263000 0.031000 1.294000 ( 1.267073)
# 0.843000 0.000000 0.843000 ( 0.846048)
# 0.936000 0.015000 0.951000 ( 0.962055)
# 0.842000 0.000000 0.842000 ( 0.839048)
# 0.843000 0.000000 0.843000 ( 0.843048)
# 0.405000 0.000000 0.405000 ( 0.410024)
答案 4 :(得分:4)
不确定您是否认为这是一项改进,但使用(map
+ compact
)作为过滤器对我来说非常笨拙。我会使用select
,因为它就是它的用途,然后抓住我关心的部分结果:
arr.each_with_index.select { |a,i| a == 'x' }.map &:last
答案 5 :(得分:2)
我将Array#index_all
定义为Array#index
,但返回所有匹配的索引。这个方法可以带参数和阻塞。
class Array
def index_all(obj = nil)
if obj || block_given?
proc = obj ? ->(i) { self[i] == obj } : ->(i) { yield self[i] }
self.each_index.select(&proc)
else
self.each
end
end
end
require 'test/unit'
class TestArray < Test::Unit::TestCase
def test_index_all
arr = ['x', 'o', 'x', '.', '.', 'o', 'x']
result = arr.index_all('x')
assert_equal [0, 2, 6], result
arr = [100, 200, 100, 300, 100, 400]
result = arr.index_all {|n| n <= 200 }
assert_equal [0, 1, 2, 4], result
end
end