1

I have an array of N elements and this array contains either 0, 1 or nil. I want to get all indexes at which nil is present or sort the array so that all nil comes first.

I am looking for an efficient way because the array size can be very large.

Here is my code

array_of data # array with lots of 1, 0 and nil temp = [] array_of_data.each_with_index {|a,i| (array_of_data[i] ? true : temp << i )} 
4
  • CPU-efficient or memory-efficient? Commented Sep 16, 2017 at 4:55
  • both if possible but more importantly CPU-efficient. Commented Sep 16, 2017 at 4:56
  • Do you need the original array to be preserved? Commented Sep 16, 2017 at 4:57
  • actually i will try both ways preserving original array and not preserving it. Commented Sep 16, 2017 at 5:00

1 Answer 1

1

Alternatives for you to benchmark:

# Indices of non-nil values res = ary.map.with_index{ |v,i| i if v }.compact res = [].tap{ |r| ary.each.with_index{ |v,i| r<<i if v } } ary.map!.with_index{ |v,i| v && i }.compact # Sorting the array so that nil comes first (possibly re-ordering the others) res = ary.sort_by{ |v| v ? 1 : -1 } ary.sort_by!{ |v| v ? 1 : -1 } # Sorting the array so that nil comes first, order of others unchanged res = ary.sort_by.with_index{ |v,i| v ? i : -1 } ary.sort_by!.with_index{ |v,i| v ? i : -1 } 
Sign up to request clarification or add additional context in comments.

1 Comment

each.with_index or each_with_index?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.