答案 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