将数组中与特定值匹配的值的索引映射到一个数组中?

3

免责声明:我是一名初学者。

我有一个仅由 0 和 1 组成、16 位数字的数组。我想要创建一个新的数组,其中只包含原始数组中值为 1 的索引值。

目前我的代码如下:

one_pos = []
    image_flat.each do |x| 
        if x == 1 
            p = image_flat.index(x)
            one_pos << p
            image_flat.at(p).replace(0)
        end
    end

image_flat数组是[0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

以上代码中,one_pos返回的是[3, 3]而不是我所期望的[3, 5]。

我错在哪里了?

4个回答

6

我错在哪里了?

当你调用时

image_flat.index(x)

它只返回image_flat数组中x的第一个条目。

我猜还有一些更好的解决方案,比如这个:

image_flat.each_with_index do |v, i|
  one_pos << i if v == 1
end

谢谢你的解释,马克西姆。这真的帮助我理解为什么.index对我不起作用! - amongmany

2
尝试在你的数组上使用 each_with_index 方法(http://apidock.com/ruby/Enumerable/each_with_index)。
image_flat = [0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

one_pos = []
image_flat.each_with_index do |value, index| 
  if value == 1 
    one_pos << index
  end
end

2
我认为这是最优雅的解决方案:

image_flat.each_index.select{|i| image_flat[i] == 1}

0

如果您正在寻找一种解决方案,该解决方案不会超出可枚举块,但需要链接的解决方案,则以下是一个解决方案。

image_flat.each_with_index.select { |im,i| im==1 }.map { |arr| arr[1] }

这是一个链式的操作,需要进行额外的查找,因此对于更大的数组,Gena Shumilkin的答案可能会更优。

这就是我最初认为Gena Shumilkin试图实现的内容,直到我意识到该解决方案使用了each_index而不是each_with_index。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接