简体   繁体   中英

Produce set of random integers with minimum intervals in Matlab

I would like to randomly produce a set of integers ranging from 1~100. After sorting the integers, the minimum interval between each integer should not be less than a 2. For example

2,4,8,10

satisfies the requirement while the following set

2,4,5,7

does not since the interval between 4 and 5 is less than 2. Is there any way to achieve this? Thanks!

N = 10; % number of integers required
delta = 2; % minimum difference required

a = randperm(100);
idx = 1;
b = a(idx);

while(length(b) < N && idx < length(a))
    idx = idx+1;
    c = abs(b - a(idx));
    if any(c < delta)
        continue;
    end
    b = [b; a(idx)];
end

b

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM