Search code examples
javascriptrandomnumbersgenerator

Generate 4 random numbers that add to a certain value in Javascript


I want a bit of javascript that will allow me to generate 4 random numbers that add up to a certain value e.g.

if

max = 20

then

num1 = 4
num2 = 4
num3 = 7
num4 = 5

or

max = 36

then

num1 = 12
num2 = 5
num3 = 9
num4 = 10

What I have so far is...

var maxNum = 20;
var quarter;
var lowlimit;
var upplimit;
var num1 = 1000;
var num2 = 1000;
var num3 = 1000;
var num4 = 1000;
var sumnum = num1+num2+num3+num4;

quarter = maxNum * 0.25;
lowlimit = base - (base * 0.5);
upplimit = base + (base * 0.5);

if(sumnum != maxNum){
    num1 = Math.floor(Math.random()*(upplimit-lowlimit+1)+lowlimit);
    num2 = Math.floor(Math.random()*(upplimit-lowlimit+1)+lowlimit);
    num3 = Math.floor(Math.random()*(upplimit-lowlimit+1)+lowlimit);
    num4 = Math.floor(Math.random()*(upplimit-lowlimit+1)+lowlimit);
}

Solution

  • This code will create four integers that sum up to the maximum number and will not be zero

    var max = 36;
    var r1 = randombetween(1, max-3);
    var r2 = randombetween(1, max-2-r1);
    var r3 = randombetween(1, max-1-r1-r2);
    var r4 = max - r1 - r2 - r3;
    
    
    function randombetween(min, max) {
      return Math.floor(Math.random()*(max-min+1)+min);
    }
    

    EDIT: And this one will create thecount number of integers that sum up to max and returns them in an array (using the randombetween function above)

    function generate(max, thecount) {
      var r = [];
      var currsum = 0;
      for(var i=0; i<thecount-1; i++) {
         r[i] = randombetween(1, max-(thecount-i-1)-currsum);
         currsum += r[i];
      }
      r[thecount-1] = max - currsum;
      return r;
    }