Created
October 28, 2012 17:30
-
-
Save tobin/3969224 to your computer and use it in GitHub Desktop.
Generate unique permutations (Matlab)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function P = uniqueperms(varargin) | |
% This function allows two possible calling formats: | |
% perms_nodupes(syms) | |
% perms_nodupes(syms,counts) | |
% | |
% Here perms_nodupes returns all permutations of the vector SYMS. | |
% COUNTS is an optional vector indicating how many times each symbol should | |
% be included. The following are equivalent: | |
% | |
% perms_nodupes([0 0 1 2]) | |
% perms_nodupes([0 1 2], [2 1 1]); | |
if nargin==1 | |
syms = unique(varargin{1}); | |
counts = arrayfun(@(x) numel(find(varargin{1}==x)), syms); | |
elseif nargin==2 | |
syms = varargin{1}; | |
counts = varargin{2}; | |
else | |
error('invalid arguments'); | |
end | |
% Remove symbols that have count==0 | |
ii = (counts==0); | |
syms(ii) = []; | |
counts(ii) = []; | |
% Check whether we have only one symbol left | |
if sum(counts)<=1 | |
P = syms; | |
return | |
end | |
N = length(syms); | |
P = zeros(0, N); | |
for ii=1:N | |
% start a permutation with syms[ii] | |
s = syms(ii); | |
q = uniqueperms(syms, counts - ((1:N)==ii)); | |
% stick the current symbol on the front of all the returned results: | |
q = [repmat(s, size(q,1), 1) q]; | |
P = [P ; q]; | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment