random order of elements in array meeting some conditions

1 view (last 30 days)
Hello!
I have a vector with levels:
levels = [20:5:80];
I am randomizing the order of presentation so that every level is used during my experiment:
b = levels(randperm(numel(levels)));
However, I want to make sure that there will be no situation that the subsequent numbers will not be higher than the previous one than 30, e.g.
b = 60 55 80 35 65 25 30 40 75 50 20 45 70;
I wrote this loop (see below) however it does not ensure my condition, it just randomise the order again... How can I modify it to make sure that?
for l = 2:(length(b)-1)
if b(l)-b(l-1)>=30
b = levels(randperm(numel(levels)));
end
end
  1 Comment
Adam
Adam on 20 Aug 2019
How 'random' do you need them to be? Obviously you could randomise them within blocks of 30 to ensure the condition, but that isn't especially random overall.

Sign in to comment.

Accepted Answer

Bruno Luong
Bruno Luong on 20 Aug 2019
Edited: Bruno Luong on 20 Aug 2019
Dynamic programming
rpermc()
%% save the rest in rpermc.m if needed
function r = rpermc()
while true
r = rpc([], 20:5:80, 30);
if ~isempty(r)
return
end
end
end
% subfunction
function r = rpc(r, s, dmax)
if isempty(s)
return
else
if isempty(r)
b = true(size(s));
else
b = s < r(end)+dmax;
end
if any(b)
i = find(b);
i = ceil(rand*length(i));
r = [r s(i)];
s(i) = [];
r = rpc(r, s, dmax);
else
r = [];
end
end
end

More Answers (1)

Rik
Rik on 20 Aug 2019
I'm not aware of any method that can do what you want. In the mean time, you can use the code below to improve the efficiency of your brute force method. Note that this does not check if there actually exists a valid permutation.
levels = 20:5:80;
satisfies_condition=@(x) all(diff(x)<30);
b = levels(randperm(numel(levels)));
while ~satisfies_condition(b)
b = levels(randperm(numel(levels)));
end

Categories

Find more on Historical Contests in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!