How to generate a vector of numbers picked from two groups with the condition that there cannot be more than 2 consecutive numbers from the same group?

2 views (last 30 days)
Dear people,
I created a vector with 26 ones, 26 twos, 26 threes and so on until the number 12. Then I shuffle these numbers in another vector so now the vector is like this a = [1 5 2 10 9 3 5...]. From these 12 different numbers some of them (let's say 1 2 3 and 4) come from the same group (group A) and the rest come from group B.
The problem is that I need them to not be more than 2 of the same group in a row (for example if I have [1 3 2..] is wrong, but if I have [1 3 6...] it's okay).
I created a loop in which I check if there are more than 2 numbers of the same group in a row, and if it is the case I reshuffle the main vector. But Matlab never stops. Do you know another possibility to achieve what I need?
Thank you so much in advance

Answers (1)

Jeff Miller
Jeff Miller on 25 Feb 2022
If I understand what you are asking, this should be close to what you want:
vecLength = 20; % how many numbers you want to generate
group1Numbers = 1:4; % specify which numbers belong to each group
group2Numbers = 5:12;
% first make a vector with group numbers 1 or 2, with a max of 2 in a row
% from the same group
groupVec = zeros(vecLength,1);
groupVec(1:2) = randi([1, 2],2,1);
for ipos=3:vecLength
if groupVec(ipos-2) == groupVec(ipos-1)
groupVec(ipos) = 3 - groupVec(ipos-1); % switch group 1 to 2 or vice versa
groupVec(ipos) = randi([1, 2],1,1);
groupVec' % this is the sequence of group numbers
% now pick numbers randomly from the pre-selected groups:
finalVec = zeros(vecLength,1);
for ipos=1:vecLength
switch groupVec(ipos)
case 1
randpos = randi([1 numel(group1Numbers)],1,1);
finalVec(ipos) = group1Numbers(randpos);
case 2
randpos = randi([1 numel(group2Numbers)],1,1);
finalVec(ipos) = group2Numbers(randpos);
finalVec' % this is the final sequence of numbers that I think you wanted

Sign in to comment.




Community Treasure Hunt

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

Start Hunting!

Translated by