FakeDIY
FakeDIY

Reputation: 1445

Randomly pair items in one list to items in another list

I'm organising a "secret santa" event and rather than do it the boring way by drawing lots I've made it into an educational exercise and did the pairings using some matlab code. The end result means that each person in the list is asked to buy a present for one other person on the list. Codewise, the problem boils down to "From this list of people, pick someone who isn't you and who hasn't been picked by someone else".

I have some code that works, but its not very robust (if there an odd number of people its possible for an infinite loop to form). I also suspect its not "truly" random. Any better ways?

names = {'Alice' 'Bob' 'Carol' 'Dave' 'Esther' 'Frank'};
picklist = names;
c = numel(names)

pairs = cell(c,2);

for ii = 1:c
    pairs(ii,1) = names(ii);
    match = 1;
    while (match == 1)
        d = ceil(rand(1)*c);
        if ((strcmp(picklist(d),names(ii)) == 0) && (strcmp(picklist(d),'picked') == 0))
            pairs(ii,2) = picklist(d);
            picklist(d) = {'picked'};
            match = 0;
        end
    end
end

pairs

Upvotes: 0

Views: 1005

Answers (2)

J_Mech
J_Mech

Reputation: 1

I wrote a script that makes sure that all pairings are different, then puts them in files with person's name as the file name and the person they are paired with in the file.

These can then be sent out to people without anyone including the person running the code knowing which people were paired:

names = {'A' 'B' 'C'}

% create two groups that are the same

Group_A = {' '};
Group_B = {' '};

% if groups are the same at any index repair

while sum(cellfun(@strcmp,Group_A,Group_B))>0;
   idx = randperm(length(names));
   Group_A = names
   Group_B = names(idx)  ;
end


% Create .txt Files

for i = 1:length(names)
    filename = sprintf('%s.txt', Group_A{i})
    fid = fopen(filename, 'w');
    fprintf(fid, '%s', Group_B{i});
end

Upvotes: 0

Nasser
Nasser

Reputation: 13173

It is too late and I might be missing something.

names     = {'Alice' 'Bob' 'Carol' 'Dave' 'Esther' 'Frank'};
idx       = randperm(length(names));
thisGroup = names(idx);
thatGroup = names( mod(idx,length(idx))+1);

gives

thisGroup = 
    'Bob'    'Alice'    'Esther'    'Dave'    'Frank'    'Carol'

thatGroup =     
    'Carol'    'Bob'    'Frank'    'Esther'    'Alice'    'Dave'

Upvotes: 4

Related Questions