;我用matlab便的程序,请高手点评
%将长度为len的区间随机分成n块,最大块不超过m(n×m>len)
%算法描述:
%1、先产生前n-1项a1、a2、a3、...、a(n-1),每一项为0~m的随机数;
%2、下面确定最后一项:
% (1)令last = len - sum(n-1);sum(n-1)表示前n-1项的和
% (2)测试last的值;
% (3)如果last满足:last>0 且 last<m,则last就是最后一项,程序结束;
% (4)如果last<0,则从前n-1项中随机挑取一项,假设是第k项,
% 从中取出0~ak的随机数s,让last = last + s,
% (5)如果last>m,则从前n-1项中随机选取一项ak,从last取出0~(m-ak)的随机数s,
% last = last - s;
% (6)重复第(2)步;
function f = rand_seq(len,n,m)
f = m*rand(1,n) %产生1行n列的随机矩阵,每项不超过m
s = len - (sum(f) - f(n)); %最后剩余s
count = 0;
index = 0;
r = 0;
while s - m > 1e-18 || s < 1e-18
while s < 1e-18
index = int16(rand*(n-1) + 1);
t = f(index); %取第i项的值
r = rand;
f(index) = t*r; %从第i项中拿出t*(1-r)加到s里
s = s + t*(1-r);
count = count + 1;
end
while s - m > 1e-18
index = int16(rand*(n-1) + 1);
t = f(index); %取第i项的值
r = rand;
f(index) = t + (m-t)*r; %向第i项中加(m-t)*r
s = s - (m - t)*r;
count = count + 1;
end
end
f(n) = s; %最后一项确定
count %输出循环次数