Recursion 002

#recursion #datastructures #devstudy #average #sum

The goal is to find the average of an array of integers using recursion.

This is what I have from last attempt found here: https://write.as/effyverse/recursion-101

Attempt 1:

def average(arr) count = arr.count if count == 1 arr[0..count-1].sum/count else average(arr[0..count-2].sum / (count-1)) * arr[count-1] end end

a = [1,2,3,4,5] p average(a) == 3

b = [0,10] p average(b) == 5

c = [1] p average(c) == 1

Mistakes made:

__Implementation Errors: – I am calling my recursion function with the wrong input. Instead of passing in an array, I am passing in the average, fully computed.

__Understanding Errors:

Attempt 2:

Find average of array of numbers using recursion

def average(arr) count = arr.count if count == 0 0 elsif count == 1 arr[0] else sum_of_all_num = average(arr[0..count-2]) * (count-1) + arr[count-1] avg = sum_of_all_num / count end end

p average([1]) == 1 p average([0,10]) == 5 p average([1,3,5,7]) == 4

Explanation of thought process for recursion call:

What is our function? average = arr.sum / arr.count

What does this tell us? arr.sum = average * arr.count

What do we know? – If we remove the last case from our average function input and express it outside of the recursive function call, we have: sum_excl_last_num = average(arr[0..count-2]) * (count-1)