我有一个数组:
["a", "b", "c", "d"]
如何确定上述数组的第一个元素在第二个数组中出现的索引:
["next", "last", "d", "hello", "a"]
第一个数组中第一个元素在上述数组中出现的索引是2;"d"属于第一个数组,在位置2处出现。
有几种方法可以做到这一点,但是朴素的方法可能足以让您开始:
tests = ["a", "b", "c", "d"]
in_array = ["next", "last", "d", "hello", "a"]
in_array.each_with_index.find do |e, i|
tests.include?(e)
end
# => ["d", 2]
您可以通过将tests
设置为Set来加快速度,这样可以避免很多O(N)的查找:
tests = Set.new([ ... ])
include?
,但是在更长的列表上速度会更快。found_test, found_index = in_array.each_with_index...
这样你就能得到两个变量而不是一个由两个元素组成的数组。记住 include?
会返回 true
或 false
,所以你不能用它来引用。另一种方式是使用 found = in_array...
,然后调用 found[0]
和 found[1]
,可能这正是你之前想做的,但你过早地这么做了。 - tadman这种方法被封装在一个函数中,返回一个数组,其中包含两个数组之间所有共有元素的索引。
def find_positions(original_array, look_up_array)
positions_array = []
original_array.each do |x|
if look_up_array.index(x) != nil
positions_array << look_up_array.index(x)
end
end
positions_array
# positions_array.first => for the first matched element
end
positions_array.first
,但这样做无法避免额外的查找。alphabet = %w(a b c d)
%w(next last d hello a).each_with_index.find {|a, _index| alphabet.index(a) }
=> ["d", 2]
%w(next last d hello a).each_with_index.select {|a, _index| alphabet.index(a) }[0]
=> ["d", 2]
# if you just need the index of the first match
%w(next last d hello a).index {|a| alphabet.index(a) }
=> 2
"a"
(而不是"d"
)“第一个在上述[第二个]数组中出现的第一个数组元素”吗? - Cary Swoveland