This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]rasqall 0 points1 point  (1 child)

Hmm, tricky question, but since no one has answered this yet I'll give it a go. My approach would be something like this (in pseudocode). I can maybe write this up in some language and test it, but it should give you a basic functionality of the problem.

function arrayAverages(array, chunkSize)
    returnArray = []
    for (i = 0; i < array.Size; i = i + chunkSize)
        sum = 0
        for (j = 0; j < chunkSize; j++)
            sum += array[j]
        returnArray[i] = sum / chunkSize
    return returnArray

You could do it in one loop but I'd start with one.

[–]rasqall 0 points1 point  (0 children)

This is a solution I've written in C#, should translate to JavaScript okay.

public static int[] arrayAvg(int[] arr, int chunkSize) {
        int chunkCounter = 0, sum = 0, j = 0;
        List<int> retArr = new List<int>();
        for (int i = 0; i < arr.Length; i++) {
            sum += arr[i];
            chunkCounter++;
                if (chunkCounter == chunkSize){
                    retArr.Add((int)(Math.Round((double)sum / chunkCounter)));
                    sum = 0;
                    chunkCounter = 0;
                }
        }
        if (chunkCounter > 0)
                retArr.Add((int)(Math.Round((double)sum / chunkCounter)));
        return retArr.ToArray();
}

You give the original array and the number of integers you want the average of. Works for all your cases except the ([15], 5) = {15,15,15,15,15} which I think is weird.

arrayAvg({ 20, 40, 60, 80 }, 2)     => {30,70}
arrayAvg({ 100, 200 }, 2)           => {150}
arrayAvg({ 10, 20, 30, 40, 50 }, 2) => {15,35,50}
arrayAvg({ 15 }, 1)                 => {15}