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.
Asked: 2023-02-13 11:00:00 +0000
Seen: 8 times
Last updated: Jan 12 '23