MATLAB: Shuffling numbers while keeping identical numbers next to each other

shuffling

Hi everyone,
Let us assume the following array:
A = [1 1 2 3 3 4 6 6 6 6]
I would like to shuffle this array while while keeping identical numbers next to each other (e.g., array B):
B = [1 1 3 3 6 6 6 6 4 2]
This means that array C is not desirable for me:
C = [1 3 1 3 6 4 6 2 6 6]
Do you have any suggestion?
Regards,
Amir

Best Answer

>> A = [1,1,2,3,3,4,6,6,6,6];
>> X = diff(find([1,diff(A),1]));
>> C = mat2cell(A,1,X);
>> Y = randperm(numel(C));
>> V = [C{Y}]
V = 2 1 1 6 6 6 6 3 3 4