我想要完成的是以下内容:
我希望从相对较小的范围创建一个整数向量,并确保所有整数都不会跟随相同的整数.
即,这是一个"合法"的载体:[1 3 4 2 5 3 2 3 5 4]
这是一个"非法"载体(自5以后5):[1 3 4 2 5 5 2 3 5 4]
我已经尝试过randi各种各样的变化randperm,当我尝试从小范围(即1到5之间的整数)生成大约100个元素的向量时,我总是被卡住.
该功能运行时间过长.
这是我做过的尝试之一:
function result = nonRepeatingRand(top, count)
result = randi(top, 1, count);
while any(diff(result) == 0)
result = randi(top, 1, count);
end
end
Run Code Online (Sandbox Code Playgroud)
任何和所有的帮助将不胜感激.谢谢 !
A. *_*nda 11
那种你正在寻找可以通过产生被定义序列的差异从1到top - 1,然后计算累积和模量 top,从随机初始值开始:
function result = nonRepeatingRand(top, count)
diff = randi(top - 1, 1, count);
result = rem(cumsum(diff) + randi(1, 1, count) - 1, top) + 1;
end
Run Code Online (Sandbox Code Playgroud)
在我的机器上,这会在0.58秒内从1:5生成1000万个数字的非重复序列.