vendredi 27 août 2021

Shuffle vector elements such that two similar elements coming together at most twice

For the sake of an example:

I have a vector named vec containing ten 1s and ten 2s. I am trying to randomly arrange it but with one condition that two same values must not come together more than twice.

What I have done till now is generating random indexes of vec using the randperm function and shuffling vec accordingly. This is what I have:

vec = [1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2];
atmost = 2;
indexes = randperm(length(vec));
vec = vec(indexes);

>> vec =
      2  1  1  1  2  1  2  1  2  1  1  1  2  2  1  2  1  2  2  2

My code randomly arranges elements of vec but does not fulfill the condition of two similar values coming at most two times. How can I do this? Any ideas?




Aucun commentaire:

Enregistrer un commentaire