amongmany
amongmany

Reputation: 87

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?

Upvotes: 3

Views: 107

Answers (4)

earth2jason
earth2jason

Reputation: 717

Here is a solution if you are looking for a solution that doesn't reach out of the enumerable block although it does require a chained solution.

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

Its chained and will require an additional lookup so Gena Shumilkin's answer will probably be more optimal for larger arrays.

This was what I originally thought Gena Shumilkin was trying to reach until I realized that solution used each_index instead of each_with_index.

Upvotes: 0

Maxim Pontyushenko
Maxim Pontyushenko

Reputation: 3053

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

Upvotes: 6

Gena  Shumilkin
Gena Shumilkin

Reputation: 713

I think this is the most elegant solution here:

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

Upvotes: 2

Aaron Washburn
Aaron Washburn

Reputation: 300

Try using each_with_index (http://apidock.com/ruby/Enumerable/each_with_index) on your array.

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

Upvotes: 2

Related Questions