mercredi 30 janvier 2019

generate 25 random numbers whose sum doesn't overcome a certain range

I set a function "generateRandom" that generates 25 random numbers in a min-max range and returns an array containing the sum of the 25 numbers followed by an array of all the 25 numbers; then I set another function "between" that takes the sum value in the array generated by the "generateRandom" function and returns the sum only if the sum is between a certain set range (8050 and 9050 in the example) otherwise it runs the "between" function until the previous condition is true.

function generateRandom(min,max) {
  let sum=0;
  let ar=[];
  for (let r=0; r<25; r++) {
    let x=Math.floor(Math.random()*(max-min+1)+min);
    sum=sum+x;
    ar.push(x);
  };
  return [sum,ar];
}

function between(x,y,limit) {
  let z=generateRandom(x,y)[0];
  while (z>limit-50||z<limit+50) {
    z=generateRandom(x,y)[0];
  };
  return z;
}

console.log(between(260,480,9000))

Can you tell me why it doesn't work?




Aucun commentaire:

Enregistrer un commentaire