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:
I originally thought that my next-to-last case is represented by
arr[0..count-2].sum
. This is wrong because my next-to-last case is actually the ARRAY object ofarr[0..count-2]
and NOT the sum of it. The sum aspect is a part of the function, not the input case. It makes no sense to view the input as a sum when the method input is the array of integers — this confusion of what my input cases are supposed to be informed the implementation error above.I originally thought that my base case would be the last input to be computed by the recursive function instead of thinking of it as the END of the recursive call, as the case where the recursion call is no longer needed.
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)
remembering that our goal is to find the average of all num so we need:
sum_of_all_num = sum_excl_last_num + arr[count-1]
calculate average:
avg = sum_of_all_num / count
refactor:
sum_of_all_num = average(arr[0..count-2]) * (count-1) + arr[count-1]
avg = sum_of_all_num / count