How can a JavaScript function be created to choose a random whole number from an array, to ultimately achieve a specific average with repeated trials?

add a comment

1

Here is an example JavaScript function that chooses a random whole number from an array and repeats trials until a specific average is achieved:

```
function randomNumToAvg(targetAvg, numList) {
let sum = 0;
let count = 0;
// sum up array items
for(let i=0; i<numList.length; i++) {
sum += numList[i];
count++;
}
// loop until target average is reached
while(sum/count < targetAvg) {
// choose a random number from array
let randIndex = Math.floor(Math.random()*numList.length);
let randNum = numList[randIndex];
// add random number to sum and increment count
sum += randNum;
count++;
}
// return average when target is achieved
return sum/count;
}
```

To use this function, simply pass in the target average and an array of whole numbers:

```
// example usage
let targetAvg = 5;
let numList = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let result = randomNumToAvg(targetAvg, numList);
console.log(result);
```

This function will choose random numbers from the input array until the average of all numbers is greater than or equal to the target average. The function then returns the final average achieved.

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Asked: ** 2023-02-13 11:00:00 +0000 **

Seen: **1 times**

Last updated: **Jan 12**

Is it feasible to utilize a Toggle Button to switch among multiple classes exceeding 2?

What is the process for generating a dynamic subdomain/URL using vue.js?

How can I create a transition on click using CSS without the need for JavaScript?

How can the style of the loader be modified while the form submission is being processed?

I'm attempting to develop a Javascript-based comments section for my website.

What are some feasible methods to enable MIDI file playback on a web browser?

Copyright QStack.ai, 2010-2023. Content on this site is licensed under the Creative Commons Attribution Share Alike 3.0 license.