Estoy tratando de obtener valores aleatorios en una matriz en la que la suma debe ser 100. El valor no necesita ser único, solo necesita tener la suma con menos del valor máximo (100).
Por ejemplo:
function getRandomNumbers(max, amountOfNumbers){ //max value that the sum of all the values in the array must have var max; //Amount of numbers that the array must have. //Example: amountOfNumbers=4 //Return: [88, 1, 2, 3, 6] var amountOfNumbers; //randomize a number from 1 to the maxnumber var randomNumber = Math.floor(Math.random() * (maxNumber - 1 + 1) + 1) var arrayOfRandoms = [] arrayOfRandoms.push(randomNumber) }
Así que mi objetivo aquí es seguir obteniendo el siguiente valor hasta que llegue a 0. La cuestión es que el siguiente valor debe ser más bajo que el último, para que la suma llegue a 100.
El rendimiento esperado sería:
// console.log(arrayOfRandoms) // [50,10,25,3,12] // [95, 3, 2] // [1, 1, 2, 3, 10, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2]
Probablemente me estoy perdiendo algo y agradezco la ayuda.
Su descripción no coincide con su ejemplo de código. Si lo que quieres hacer es:
Para lograr esto entonces:
function getRandomNumbers(max, amountOfNumbers) { // let's check that we can achieve the goal. Since we need to get a number from 1 to `max` as many times as `amountOfNumbers` then `max` should always be greater than `amountOfNumbers`. // also, max should be greater than 0. if (amountOfNumbers > max || max <= 0) { throw new Error( "Please specify a `max` greater than the amount of numbers" ); } //`max` is the value that the sum of all the values in the array must have //Amount of numbers that the array must have. //Example: amountOfNumbers=4 //Return: [88, 1, 2, 3, 6] var arrayOfRandoms = []; var sumOfRandoms = 0; for (var i = 0; i < amountOfNumbers; i++) { // calculates the maximum number allowed for this iteration. // this is, the max value minus the amount we already have in the array. // we also need to think on how many spots in the array are left, since the minimum number is 1, then we need to leave enough number to fill the spots at least by 1s. var maxForThisIteration = max - sumOfRandoms - (amountOfNumbers - i); // calculates the random number to add to the array. // for example, if the max number for this iteration is 5 then we look for a random number from 0 to 4 and then add 1 (to get a random number from 1 to 5) var randomNumber = Math.floor(Math.random() * (maxForThisIteration - 1)) + 1; // we add the random number to the array arrayOfRandoms.push(randomNumber); // we add the random number to the sum, so we can calculate the max value for the next iteration sumOfRandoms += randomNumber; } return arrayOfRandoms; } var result = getRandomNumbers(100, 4); console.log("result", result);