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 vues (au cours des 30 derniers jours)
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

Réponses (1)

Jeff Miller
Jeff Miller le 25 Fév 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
else
groupVec(ipos) = randi([1, 2],1,1);
end
end
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);
end
end
finalVec' % this is the final sequence of numbers that I think you wanted
  3 commentaires
Jeff Miller
Jeff Miller le 26 Fév 2022
That's a much tougher problem, which I do not know how to solve.
I am not surprised that MATLAB never finds a solution, since there are so many more random sequences that are not solutions than there are sequences that are solutions.
I would try to generate an acceptable sequence of 1's and 2's first. Once you had that sequence, you could replace each 1 or 2 with a number from its corresponding group. But getting a 1's & 2's sequence satisfying your constraints does not look easy.
Sorry I cannot be more help.
Trisia Cinca Tomás
Trisia Cinca Tomás le 27 Fév 2022
That's what I thought.
Thank you so much Jeff for your help.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by