mardi 13 novembre 2018

Shuffle array while spacing repeating elements

I'm trying to write a function that shuffles an array, which contains repeating elements, but ensures that repeating elements are not too close to one another.

This code works but seems inefficient to me:

function shuffledArr = distShuffle(myArr, myDist)
% this function takes an array myArr and shuffles it, while ensuring that repeating 
% elements are at least myDist elements away from on another    

% flag to indicate whether there are repetitions within myDist
reps = 1;
while reps 

    % set to 0 to break while-loop, will be set to 1 if it doesn't meet condition
    reps = 0;  

    % randomly shuffle array
    shuffledArr = Shuffle(myArr);

    % loop through each unique value, find its position, and calculate the distance to the next occurence
    for x = 1:length(unique(myArr))
        % check if there are any repetitions that are separated by myDist or less
       if any(diff(find(shuffledArr == x)) <= myDist)
           reps = 1;
       break;
   end
end
end

This seems suboptimal to me for three reasons:

1) It may not be necessary to repeatedly shuffle until a solution has been found.

2) This while loop will go on forever if there is no possible solution (i.e. setting myDist to be too high to find a configuration that fits). Any ideas on how to catch this in advance?

3) There must be an easier way to determine the distance between repeating elements in an array than what I did by looping through each unique value.

I would be grateful for answers to points 2 and 3, even if point 1 is correct and it is possible to do this in a single shuffle.




Aucun commentaire:

Enregistrer un commentaire