Ruby数组元素索引

时间:2019-01-14 10:50:44

标签: ruby-on-rails arrays ruby

考虑一下,我有一个整数元素数组。我试图在其中找到一长串重复数字开始的索引。

my_array = [100, 101, 100, 102, 100, 100, 101, 100, 250, 251, 253, 260, 250, 200, 100, 100, 100, 100, 100, 100, 100, 100, 100, 120]

贝勒是我尝试查找索引的方法。有人可以建议我做些更优化,更正确的方法吗?

my_array.each with_index do |e, x|
  match = e.to_s * 5
  next_10 = my_array[x + 1, 5].join()

  if match == next_10
    puts "index #{x}"
    break
  end
end

#index 14

4 个答案:

答案 0 :(得分:2)

my_array.index.with_index{|value,index| my_array[index,6].uniq.size==1}

这是一种调整,如果您的意思是按照代码的样子“优化”。如果您的意思是优化性能。它不合适。

答案 1 :(得分:1)

在第一次迭代中,我得到了重复元素序列的数组,然后继续进行逻辑处理,

groups = my_array[1..-1].inject([[my_array[0]]]) { |m, n| m.last[0] == n ? m.last << n : m << [n]; m }
# => [[100], [101], [100], [102], [100, 100], [101], [100], [250], [251], [253], [260], [250], [200], [100, 100, 100, 100, 100, 100, 100, 100, 100], [120]]

groups[0,groups.index(groups.sort { |a,b| a.count <=> b.count }.last)].flatten.count
# => 14

使用正则表达式,它可以精确而简单。

答案 2 :(得分:1)

my_array = [100, 101, 100, 102, 100, 100, 101, 100, 250, 251, 253, 260, 250, 200, 100, 100, 100, 100, 100, 100, 100, 100, 100, 120]


index_and_repetitions = lambda { |my_array|
  stk = {}
  previous = my_array[0]
  last_index = 0
  stk[last_index] = 1
  my_array.drop(0).each_with_index{|item, index|
    if item == previous
      stk[last_index] += 1
    else
      last_index = index
      stk[last_index] = 1
      previous = item
    end
  }
  stk
}

stk = index_and_repetitions.call(my_array)
puts stk.key(stk.values.max)

您可以在这里找到benchmark results(compared to others answers)

答案 3 :(得分:1)

我假设目标是在给定数组中找到最长的相等元素序列的第一个元素的索引。

my_array = [100, 101, 100, 102, 100, 100, 101, 100, 250, 251, 253, 260, 250, 200,
            100, 100, 100, 100, 100, 100, 100, 100, 100,
            120]

此处为14,即100的索引,后面是另外8个100

我们可以按照以下步骤进行操作。

my_array.each_index.chunk { |i| my_array[i] }.
         max_by { |_,a| a.size }.
         last.
         first
           #=> 14

步骤如下。

enum0 = my_array.each_index
  #=> #<Enumerator: [100, 101, 100,..., 100, 120]:each_index> 

通过将其枚举转换为数组,我们可以看到将由该枚举器生成的元素。

enum0.to_a
  #=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
  #    17, 18, 19, 20, 21, 22, 23]

继续

enum1 = enum0.chunk { |i| my_array[i] }
  #=> #<Enumerator: #<Enumerator::Generator:0x000058d8d09ec8a0>:each> 

鉴于上述表达式的返回值,enum1可以被视为复合枚举器,尽管Ruby没有这样的概念。让我们看看将生成enum1的值。

enum1.to_a
  #=> [[100, [0]], [101, [1]], [100, [2]], [102, [3]], [100, [4, 5]],
  #    [101, [6]], [100, [7]], [250, [8]], [251, [9]], [253, [10]],
  #    [260, [11]], [250, [12]], [200, [13]],
  #    [100, [14, 15, 16, 17, 18, 19, 20, 21, 22]],
  #    [120, [23]]]

继续

a = enum1.max_by { |v,a| a.size }
  #=> [100, [14, 15, 16, 17, 18, 19, 20, 21, 22]]

由于在该块中未使用v,因此该表达式通常被编写为:

a = enum1.max_by { |_,a| a.size }

下划线(有效的局部变量)的存在向读者发出信号,表示该块变量未用于块计算中。最后两个步骤如下。

b = a.last
  #=> [14, 15, 16, 17, 18, 19, 20, 21, 22] 
b.first
  #=> 14 

请参见Enumerable#chunkEnumerable#max_by