dinex
dinex

Reputation: 377

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!

Upvotes: 0

Views: 78

Answers (1)

Prakhar
Prakhar

Reputation: 325

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

Upvotes: 4

Related Questions