生成4个随机数,这些随机数加到Javascript中的某个值上 [英] Generate 4 random numbers that add to a certain value in Javascript

查看:319
本文介绍了生成4个随机数,这些随机数加到Javascript中的某个值上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一些JavaScript,可以让我生成4个随机数字,这些数字加起来等于某个值,例如.

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

如果

max = 20

然后

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

max = 36

然后

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);
}

推荐答案

此代码将创建四个整数,它们的总和为最大,并且不为零

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);
}

这将创建thecount个整数,它们加起来为max并将其返回到数组中(使用上面的randombetween函数)

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;
}

这篇关于生成4个随机数,这些随机数加到Javascript中的某个值上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆