获取数组中值为nil的所有索引

时间:2017-09-16 04:52:03

标签: arrays ruby performance sorting memory-efficient

我有一个N元素数组,此数组包含01nil。 我希望得到nil存在的所有索引或对数组进行排序,以便所有nil都排在第一位。

我正在寻找一种有效的方法,因为数组大小可能非常大。

这是我的代码

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 )}

1 个答案:

答案 0 :(得分:1)

您进行基准测试的替代方案:

# 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 }
相关问题