How to check that only one value in an array is nonzero?

Given an array like: [0,1,1]

How can I elegantly verify that: only one element has a nonzero value and the rest 0?

(Thus, the above-mentioned array can not check this check until the array will take place: [1,0,0])

+3
source share
3 answers
my_array.count(0) == my_array.length-1

If speed is important, for very large arrays, where you might need to return early if you find a second nonzero, it is possible:

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
+8
source

Select no more than two nonzero elements and check if only one element is 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

Ruby 1.8.7, , select , " ". , , Ruby.

+6

Thanks for all your answers!

I also decided:

input_array = [0,0,0]
result = input_array - [0]
p result.size == 1 && result[0] == 1

Ruby, I love you!

+2
source

Source: https://habr.com/ru/post/1782397/


All Articles