random order of elements in array meeting some conditions

조회 수: 1 (최근 30일)
Katarzyna Dragun
Katarzyna Dragun 2019년 8월 20일
댓글: Katarzyna Dragun 2019년 8월 20일
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
Adam
Adam 2019년 8월 20일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Bruno Luong
Bruno Luong 2019년 8월 20일
편집: Bruno Luong 2019년 8월 20일
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

추가 답변 (1개)

Rik
Rik 2019년 8월 20일
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

카테고리

Help CenterFile Exchange에서 Historical Contests에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by