How to Find the Means of an Array, By Counting The Digit Simultaneously

Excuse me all, I want to ask one question, it was bothering me right now. I think it’s a quite simple. But i don’t know how to solve it. Perhaps you all know about this.

This question is an array like this [3,4,5] and the answer is 5

The algorithm to get the answer is by doing this things

3  4   5
/  /
4   5
/
5

(Every decimal number will be rounds up to the next largest integer)

So the answer that we will get is 5.


For other question is like [8,1,8,8,0] the output will be 7

enter image description here

Is there is someone that maybe knows how to solve this, i use javascript for this algorithm.

But still can’t finding the way to solve this

Every help would be nice,

thanks

Answer

You could iterate whoile you have a length greater than one and map a new array of a smaller array.

let array = [8, 1, 8, 8, 0];

console.log(...array);
while (array.length > 1) {
    let l = array[0]
    array = array.slice(1).map(r => {
        let v = Math.ceil((l + r) / 2);
        l = r;
        return v;
    });
    console.log(...array);
}