ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Ruby] exercise _ All Else Equal
    coding for food 2022. 8. 7. 14:08

    Write a method all_else_equal that takes in an array of numbers. The method should return the element of the array that is equal to half of the sum of all elements of the array. If there is no such element, the method should return nil.

    def all_else_equal(arr)
    
    end
    
    p all_else_equal([2, 4, 3, 10, 1]) #=> 10, because the sum of all elements is 20
    p all_else_equal([6, 3, 5, -9, 1]) #=> 3, because the sum of all elements is 6
    p all_else_equal([1, 2, 3, 4])     #=> nil, because the sum of all elements is 10 and there is no 5 in the array
    # my code
    
    def all_else_equal(arr)
      sum = 0
       
      arr.each do |num|
      	sum += num
      end
      half = sum / 2
    
      if arr.include?(half) 
        return half
      else
        return nil
      end
    end
    
    p all_else_equal([2, 4, 3, 10, 1]) #=> 10, 
    p all_else_equal([6, 3, 5, -9, 1]) #=> 3, 
    p all_else_equal([1, 2, 3, 4])     #=> nil,
    # solution 
    
    def all_else_equal(arr)
      sum = sum_array(arr)
    
      arr.each do |ele|
        if ele == sum / 2.0
          return ele
        end
      end
    
      return nil # default return nil
    end
    
    def sum_array(arr)
      sum = 0
    
      arr.each do |num|
        sum += num
      end
    
      return sum
    end
    
    p all_else_equal([2, 4, 3, 10, 1]) #=> 10
    p all_else_equal([6, 3, 5, -9, 1]) #=> 3
    p all_else_equal([1, 2, 3, 4])     #=> false
Designed by Tistory.