how to create a list of random number with a minimum difference between each number?

Hi,
I am trying to create a list of 'n' random numbers within a range(1,m) and the difference between adjacent numbers need to be at least 'd'.
The list needs to be sorted and no repetion allowed.
I can do the same in python using
% r = m - ((m - 1) * (n - 1))
% = 30 - ((3-1) * (6-1)) = 30 - 2*5 = 20
%[(d-1)*i + x for i, x in enumerate(sorted(random.sample(range(r), n)))]
print([2*i + x for i, x in enumerate(sorted(random.sample(range(20), 6)))])
>>[2, 5, 14, 20, 24, 28]
In the above code, I am trying to generate a sorted list of 6 random numbers from 0-30, with a minimum difference between each adjacent element of at least 3.
Can some one plese suggest me how can I do something similar in matlab?

11 Comments

Not clear. Could you give an example ?
If the range is 1:100 and d = 6, you expect something like
v = 98 91 80 74 60 ...
such that v(1:n-1) -v(2:n) >= 6
?
That is correct output, in that output, d=3, n=6 and m = 30. But I got that output using python. I am trying to write a similar code in MATLAB but I am unable to do so. I am not that experienced with MATLAB.
So, above what I did is, I was trying to generate 6 random numbers from 0-30, with a minimum difference between each adjacent element of at least 3.
But the numbers are in the wrong order, at least according to your description.
I am sorry for the confussion, I have corrected my explaination.
So the list of numbers does not need to be increasing or decreasing ?
So [2 14 4 28 20 4] (not ordered, repetitions allowed) (d=3, n=6 and m = 30) would be acceptable in your test case ?
Sorry for the confussion again, by either I meant, it can either be increasing or decresing.
If you take [2 14 4 28 20 4], after sorting it will be [2 4 4 14 20 28 ], and the difference between 1st 3 elements is less than 3 so it wont be acceptable. if it was [2 5 8 14 20 28 ] then it would be acceptable.

Sign in to comment.

Answers (1)

You can brute force it.
m=200;%randomn numbers between 1-200
n=50;%array length
d=20;%minimum distance
a=randi(m,100000,n);%make sifficiently large
D=abs(diff(a,[],2));
idx=D>=d;
f=find(sum(idx,2)==n-1);
randNums=a(f,:);%rows of array having randomn numbers with adjacent elements being at least d apart

4 Comments

How do you want to get a sorted array of length 50 with elements minimum 10 apart if you only choose random numbers between 1-200 ? Maximum array length in this case is 20 .
Below works but the randomn numbers will be skewed towards the high-side of the interval.
m=2000;
n=10;
d=5;
r=1:m;
R=[];
while 1
for k=1:n
if length(r)+k<n||isempty(r)
r=1:m;
R=[];
break;
end
p=randperm(length(r),1);
R=[R,r(p)];
r=r(r>(r(p)+d));
end
if ~isempty(R)
break;
end
end

Sign in to comment.

Products

Release

R2022a

Asked:

on 2 Aug 2022

Commented:

on 2 Aug 2022

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!