How to check that only one value in an array is non-zero?
Given an array like : [0,1,1]
How can I elegantly check that: Only one element has a non-zero value and that the others are 0?
(So the above array will fail the check while this array will pass : [开发者_如何转开发1,0,0]
)
my_array.count(0) == my_array.length-1
If speed is important, for very large arrays where you might need to return early upon detecting a second non-zero, perhaps:
def only_one_non_zero?( array )
found_non_zero = false
array.each do |val|
if val!=0
return false if found_non_zero
found_non_zero = true
end
end
found_non_zero
end
Select at most two non-zero elements, and check if exactly one item was available.
>> [0,1,1].select {|x| !x.zero?}.take(2).size == 1
=> false
>> [0,1,0].select {|x| !x.zero?}.take(2).size == 1
=> true
>> [1,2,3].select {|x| !x.zero?}.take(2).size == 1
=> false
Works fine in Ruby 1.8.7, but note that select
returns an array, so it's not "optimally lazy". Here's a blog post showing how to make some lazy enumerators in Ruby.
Thanks for all your answers!
I solved too:
input_array = [0,0,0]
result = input_array - [0]
p result.size == 1 && result[0] == 1
Ruby, I love you!
精彩评论