I am trying to find the average the sum of digits of a number.
For example, for the number 123, the sum of digits of 123 is 6 and the number of digits in 123 is 3. So, the average of digits of 123 is 6/3 = 2.
I've only gotten as far as trying to find the sum through recursion unfortunately and often comes up as undefined. If I could figure this out I could find the average comfortably.
function averageOfDigits(number) {
// Make the whole number into a string first to get the individual digits
let arrOfStr = number.toString().split('');
// Convert this array into integers
let arrOfNum = arrOfStr.map(parseFloat)
// Find sum of these digits using recursion
let sum = function sumRecursion (arrOfNum) {
if (arrOfNum.length === 1) {
return arrOfNum[0]
} else {
return arrOfNum.pop() sum(arrOfNum)
}
}
}
console.log(averageOfDigits(999))
CodePudding user response:
You were close. Your implementation is setting sum
equal to the recursive function, so that function is never getting called inside averageOfDigits
. I think the confusing part was referring to the same function by two different names.
Here I define the sum
function once, then call it twice. First is the internal recursive call, and second is in the return
statement.
function averageOfDigits(number) {
// Make the whole number into a string first to get the individual digits
let arrOfStr = number.toString().split('');
// Convert this array into integers
let arrOfNum = arrOfStr.map(parseFloat)
// Find sum of these digits using recursion
function sum(arrOfNum) {
if (arrOfNum.length === 1) {
// base case reached
return arrOfNum[0];
} else {
// return first digit recursive call
return arrOfNum.pop() sum(arrOfNum);
}
}
return sum(arrOfNum);
}
console.log(averageOfDigits(999))
You can finish off the averageOfDigits
function by replacing the return
statement with your own code. Right now it just returns the sum.
CodePudding user response:
It's missing the initial call to the recursive function.
Hint:
return (function sum(arr) {
if (arr.length === 1) {
return arr[0]
} else {
return arr.pop() sum(arr)
}
}(arrOfNum))