Skip to content

Instantly share code, notes, and snippets.

@jaredhowland
Forked from tobin/uniqueperms.m
Created March 14, 2016 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaredhowland/e4a5e0a28bcd0e7209eb to your computer and use it in GitHub Desktop.
Save jaredhowland/e4a5e0a28bcd0e7209eb to your computer and use it in GitHub Desktop.
Generate unique permutations (Matlab)
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