• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

80
Vistas
Select only the values that match the required sum from a random range in Javascript

I'm trying to get random values into an array that the sum should be 100. The value don't need to be unique, it just needs to have the sum with less than the maximum value (100).

For example:

    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)


    }

So my goal here is to keep getting the next value until it reaches 0. The thing is, the next value must be lower than the last one, so the sum gets to 100.

The expected return would be:

// 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]

I'm probably missing something and appreciate the help.

almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your description doesn't match your code example. If what you want to do is:

  • I want to get an array of random numbers.
  • I want the sum of those numbers to not exceed an specified value.
  • I also want to specify how many items are in the array.

To achieve this then:

    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);
almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda