MATLAB: Shuffle vector with constraints

constraintsshuffle

Hi,
I have an array of 50 1's, 50 2's, etc up to 50 8's. I would like to shuffle them with the constraint that two consecutive numbers cannot be the same. I tried several options but most are very cpu intensive or did not yield a good result. Are there computation efficient solutions to this problem?

Best Answer

A brute force method works fairly well in this scenario - 1) start with a shuffled version of the sequence, 2) find repeats, 3) swap any repeats to different locations... goto 2 (rinse and repeat). This sort of method would likely be terrible if you had fewer characters in your sequence, but for nine unique elements, it seems to halt very quickly.
Making your sequence:
seq = repmat([1:8],50,1); %make sequence

seq = [seq(:);repmat(9,30,1)]; %make sequence
Doing the reshuffling:
seq = seq(randperm(numel(seq))); %initial shuffle
old_idx= unique(find(diff(seq)==0));%find repeats

while ~isempty(old_idx), %continue until no repeats
new_idx = unique(setdiff([1:length(seq)],old_idx)); %find new spots
new_idx = new_idx((randi(length(new_idx),length(old_idx),1)))';
seq([new_idx;old_idx],:) = seq([old_idx;new_idx],:); %swap
old_idx= unique(find(diff(seq)==0));%find repeats
end