将整数拆分为随机数之和 [英] Split integer into sum of random numbers
本文介绍了将整数拆分为随机数之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我们有一个整数 16 .
是否存在一个函数,该函数返回组成其 sum 的 random 个数字数组?
Is there a function, that returns random array of numbers, which compose its sum?
例如7 1 2 4 1 1或1 5 2 3 6
For example 7 1 2 4 1 1 or 1 5 2 3 6
我想知道是否存在一些用JavaScript做到这一点的优雅方法.
I wonder if some elegant method of doing this in JavaScript exists.
推荐答案
不存在现有功能,例如:
No there's not existing function, but e.g.:
var n = 16;
var a = [];
while (n > 0) {
var s = Math.round(Math.random()*n);
a.push(s);
n -= s;
}
a
包含数组.
这篇关于将整数拆分为随机数之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文