David G
David G

Reputation: 96835

JavaScript challenge: Create an average-calculating function using recursion?

I've had trouble writing this code. I'm supposed to make a function that can take either an array of numbers or the arguments array and calculate the average without using a for or while loop. It says I have to use recursion. How do I do this?

Upvotes: 1

Views: 1317

Answers (5)

David G
David G

Reputation: 96835

I was able to finish it myself thanks to what you guys suggested. I was confused on how to go about the actual average calculation until after reading what you guys posted. If this code can be improved please tell! Thanks!

function mean( list, more ) {

    if ( more ) {

        list = [].slice.call( arguments );

    } else if ( !list || list[0] === undefined ) return;

    var a = list,
        b = list.length;


    return (function execute() {

        if ( !a.length ) return 0;

        return ( a.pop() / b ) + execute();

    })();

}

Upvotes: 2

nnnnnn
nnnnnn

Reputation: 150070

Here's what I came up with:

function av(nums, i, t) {
   if (!Array.isArray(nums))
       return av([].slice.call(arguments));
   if (t === void 0){
       if (nums.length === 0)
          return;
       return av(nums, nums.length-1, 0);
   }
   t += nums[i];   
   if (i > 0)
       return av(nums, i-1, t);
   return t / nums.length;
}

Accepts an array of numbers, or if the first param is not an array assumes all arguments are numbers. (No error checking for non-numeric data like av('a','x').) Returns undefined if array is empty or no params are supplied.

alert( av([1,2,3,4]) );   // 2.5
alert( av(1,2,3,4,5) );   // 3

Assumes Array.isArray() (or an appropriate shim) is available.

Upvotes: 0

user1473628
user1473628

Reputation:

Here it is but by looking at it you agree to understand it:

http://jsfiddle.net/sparebyte/kGg9Y/1/

function calcAverage(nums, total, count) {
    if(isNaN(count)) {
        // First iteration: Init Params
        return calcAverage(nums, 0, nums.length);
    }
    if(nums.length) {
        // Middle itrations: Get a total
        total = nums.pop() + total;
        return calcAverage(nums, total, count)
    } else {
        // Last iteration: Find the total average
        return total / count     
    }
};

Upvotes: 1

Tim Christensen
Tim Christensen

Reputation: 381

function average(set, memo, total) {
  memo || (memo = 0);
  total || (total = set.length);
  if (set.length === 0) return memo / total;
  return average(set.slice(1, set.length), (memo + set[0]), total);
}

You call it like this:

average([1,2,3,4]); // 2.5

Upvotes: 0

pbond
pbond

Reputation: 1927

I assume you're familiar with recursion.

Just implement a recursive function with an index argument to keep track of where you are, and add the numbers to the same variable. Then at the end, divide by the size of your array.

Edit: As Kranklin points out in a comment, using pop you won't even need the index argument. (You will need to store the size of the array before iterating).

Upvotes: 1

Related Questions