August 2020
Intermediate to advanced
508 pages
11h 53m
English
The following Ruby method accepts an array of numbers and returns the mean average of all its even numbers. How would we express its efficiency in terms of Big O?
| | def average_of_even_numbers(array) |
| | |
| | # The mean average of even numbers will be defined as the sum of |
| | # the even numbers divided by the count of even numbers, so we |
| | # keep track of both the sum and the count: |
| | |
| | sum = 0.0 |
| | count_of_even_numbers = 0 |
| | |
| | # We iterate through each number in the array, and if we encounter |
| | # an even number, we modify the sum and the count: |
| | |
| | array.each do |number| |
| | if number.even? |
| | sum += number |
| | count_of_even_numbers += 1 |
| | end |
| | end |
| | |
| | # We return the mean average: |
| | |
| | return |
Read now
Unlock full access