Soy nuevo en javascript y no puedo encontrar la manera de resolver este problema. Tengo un valor fijo de 88,3 y necesito 12 números aleatorios entre 6,0 y 9,99 que cuando los sumo todos coincidan con 88,3.
Hasta ahora logré generar números aleatorios dentro de un rango usando este código:
/** * Returns a random number between min (inclusive) and max (exclusive) */ function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } /** * Returns a random integer between min (inclusive) and max (inclusive). * The value is no lower than min (or the next integer greater than min * if min isn't an integer) and no greater than max (or the next integer * lower than max if max isn't an integer). * Using Math.round() will give you a non-uniform distribution! */ function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; }¿Alguien podría ayudarme?
Aquí hay una manera de lograr el resultado deseado.
La solución original es esta: https://stackoverflow.com/a/19278621/17175441 que modifiqué para tener en cuenta el límite del rango de números.
Tenga en cuenta que probablemente haya mejores formas de hacer esto, pero esto hace el trabajo por ahora:
function generate({ targetSum, numberCount, minNum, maxNum }) { var r = [] var currsum = 0 for (var i = 0; i < numberCount; i++) { r[i] = Math.random() * (maxNum - minNum) + minNum currsum += r[i] } let clamped = 0 let currentIndex = 0 while (currsum !== targetSum && clamped < numberCount) { let currNum = r[currentIndex] if (currNum == minNum || currNum == maxNum) { currentIndex++ if (currentIndex > numberCount - 1) currentIndex = 0 continue } currNum += (targetSum - currsum) / 3 if (currNum <= minNum) { r[currentIndex] = minNum + Math.random() clamped++ } else if (currNum >= maxNum) { r[currentIndex] = maxNum - Math.random() clamped++ } else { r[currentIndex] = currNum } currsum = r.reduce((p, c) => p + c) currentIndex++ if (currentIndex > numberCount - 1) currentIndex = 0 } if (currsum !== targetSum) { console.log(`\nTargetSum: ${targetSum} can't be reached with the given options`) } return r } const numbers = generate({ targetSum: 88.3, numberCount: 12, minNum: 6, maxNum: 9.99, }) console.log('number = ', numbers) console.log( 'Sum = ', numbers.reduce((p, c) => p + c) )