Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping the index of values in an array that match a specific value?

Disclaimer, I'm a beginner.

I have an array that is 16 digits, limited to 0's and 1's. I'm trying to create a new array that contains only the index values for the 1's in the original array.

I currently have:

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

The image_flat array is [0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

With the code above, one_pos returns [3, 3] rather than the [3, 5] that I'd expect.

Where am I going wrong?

like image 515
amongmany Avatar asked Dec 08 '25 06:12

amongmany


1 Answers

Where am I going wrong?

When you call

image_flat.index(x)

It only returns first entry of x in image_flat array.

I guess there are some better solutions like this one:

image_flat.each_with_index do |v, i|
  one_pos << i if v == 1
end
like image 135
Maxim Pontyushenko Avatar answered Dec 11 '25 01:12

Maxim Pontyushenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!