随机整数(有限制)在不使用求解器的情况下添加总和?高强

时间:2017-03-13 18:29:09

标签: excel matlab random numbers

我正在尝试选择介于0和0之间的随机整数。 6.然后,重复该过程7次,得到随机整数,恰好合计为40。

如果可能的话,我想在Excel中使用Macros或MATLAB。

我应该在这里填写什么问题?:

enter image description here

1 个答案:

答案 0 :(得分:0)

以下方法迭代计算随机数的允许边界,以便可以达到所请求的总和。

N = 7; % number of random integers to generate
total = 40; % requested sum
from = zeros(N, 1); % minimum values
to = 6*ones(N, 1); % maximum values


value = zeros(N, 1); % allocate space for solution
currentTotal = 0; % sum up to loop iteration i
for i=1:N
    minTotal = currentTotal + to(i) + sum(from(i+1:N)); % minimal sum we can achieve if the current random number equals the maximum value
    maxTotal = currentTotal + from(i) + sum(to(i+1:N)); % maximal sum we can achieve if the current random number equals the minimum value
    if minTotal > total
      to(i) = to(i) - (minTotal - total); % update to maximal allowed value
    end
    if  maxTotal < total % update the minimal allowed value
      from(i) = from(i) + (total - maxTotal);
    end
    value(i) = randi([from(i) to(i)]); % calculate the random value
    currentTotal = currentTotal + value(i); % calculate the updated sum
end

sum(value) == total