Ask Your Question
4

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?

asked 2023-02-13 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-01-12 20:00:00 +0000

huitzilopochtli gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

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

Seen: 8 times

Last updated: Jan 12 '23