Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find indices of elements that match a given condition

Tags:

arrays

ruby

Given an array, how can I find all indices of elements those match a given condition?

For example, if I have:

arr = ['x', 'o', 'x', '.', '.', 'o', 'x'] 

To find all indices where the item is x, I could do:

arr.each_with_index.map { |a, i| a == 'x' ? i : nil }.compact   # => [0, 2, 6] 

or

(0..arr.size-1).select { |i| arr[i] == 'x' }   # => [0, 2, 6] 

Is there a nicer way to achieve this?

like image 588
Misha Moroshko Avatar asked Dec 01 '12 13:12

Misha Moroshko


People also ask

How do you find the index of list elements that meet a condition in python?

Use a list comprehension. Use enumerate() to create a list of (index, value) tuples from the input list a_list . Use a list comprehension on this list of tuples to select every index that corresponds to a value that meets the given condition, and return the selections as a list.

How do I find the index of a specific element?

To find the index of an element in a list, you use the index() function. It returns 3 as expected. However, if you attempt to find an element that doesn't exist in the list using the index() function, you'll get an error. To fix this issue, you need to use the in operator.

How do you find the index of an element in an array?

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

How do you get the index of an element in a list in C?

To find the index of specified element in given Array in C programming, iterate over the elements of array, and during each iteration check if this element is equal to the element we are searching for.


2 Answers

Ruby 1.9:

arr = ['x', 'o', 'x', '.', '.', 'o', 'x'] p arr.each_index.select{|i| arr[i] == 'x'} # =>[0, 2, 6] 

Code

like image 82
steenslag Avatar answered Sep 30 '22 06:09

steenslag


Another way:

arr.size.times.select {|i| arr[i] == 'x'} # => [0, 2, 6] 

EDIT:

Not sure if this is even needed, but here they are.

Benchmarks:

arr = 10000000.times.map{rand(1000)};  Benchmark.measure{arr.each_with_index.map { |a, i| a == 50 ? i : nil }.compact} 2.090000   0.120000   2.210000 (  2.205431)  Benchmark.measure{(0..arr.size-1).select { |i| arr[i] == 50 }} 1.600000   0.000000   1.600000 (  1.604543)  Benchmark.measure{arr.map.with_index {|a, i| a == 50 ? i : nil}.compact} 1.810000   0.020000   1.830000 (  1.829151)  Benchmark.measure{arr.each_index.select{|i| arr[i] == 50}} 1.590000   0.000000   1.590000 (  1.584074)  Benchmark.measure{arr.size.times.select {|i| arr[i] == 50}} 1.570000   0.000000   1.570000 (  1.574474) 
like image 38
AGS Avatar answered Sep 30 '22 07:09

AGS