// Generate all permutations of {1,2,...,N} // Recursive method // SciLab source code // Maurice Clerc 2007-10-02 clear //--------------------------------------------------------- function permutations=permu(N,cycle) permutations=[]; // Just because SciLab is too stupid to understand that // "permutations" is necessarily initialised by the code below if N==1 then permutations(1,1)=1; else nPerm=0; //cycle = 0 => Generate all permutations of size N-1 // = 1 => Generate all "cycles" of size N-1 perms=permu(N-1,cycle); // For each of these permutations of N-1 elements // generate N permutations of N elements // by inserting the number N for p=1:size(perms,1) // For each permutation for i=1:N-cycle // For each position nPerm=nPerm+1; select i case 1 permutations(nPerm,1)=N; permutations(nPerm,2:N)=perms(p,1:N-1); case N permutations(nPerm,1:N-1)=perms(p,1:N-1); permutations(nPerm,N)=N; else permutations(nPerm,1:i-1)=perms(p,1:i-1); permutations(nPerm,i)=N; permutations(nPerm,i+1:N)=perms(p,i:N-1); end // select end // for i end // for p end // if N==1 endfunction //--------------------------------------------------------- function same=compareCycle(p1,p2) // Check if p1 and p2 are in fact the same cycle N=length(p1); first=p1(1); for i=1:N // if p2(i)==first then break; end end for j=2:N k=i+j-1; if k>N then k=k-N; end if p2(k)~=p1(j)then same=0; return; end end same=1; endfunction //--------------------------------------------------------- //Inout N=8; // Size of the permutations cycle=1; // 0 => all permutations // 1 => only the ones that are different by applying any "rotation" //Output file saveFile=mopen('permut.txt','w'); // Generate permutations x=permu(N,cycle); nbPermu=size(x,1); if cycle==0 then printf("\n%i permutations of %i elements\n ",size(x,1),N); else printf("\n%i cycles of %i elements\n",size(x,1),N); end // Save on a file mfprintf(saveFile,"%i %i\n",size(x,1),N); for i=1:size(x,1) for j=1:N mfprintf(saveFile,'%i ',x(i,j)); end mfprintf(saveFile,"\n"); end