Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

javascript - 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...